1

I have text file with symbols (sss7775aaaa 4444a 555dussns6 7djshs8 4sssss sssss oooo) and I need to find only whose words, which has numbers in.

I think program somehow should put all symbols seperated by spaces into array and then chech every single array element. But I'm not sure how to do it.

Thanks.

Max_insane
  • 23
  • 1
  • 5
  • split the string by space, and filter by the names with numbers in – dangee1705 Nov 18 '20 at 17:30
  • divide your problem in 3 parts. 1) Read a txt file in python. 2) Convert the string into array by splitting on whitespaces. 3) Iterating over the array (also known as looping over array) and the putting then filtering (use if else clauses) it and storing it in new array. – Ajay Nov 18 '20 at 17:40

4 Answers4

3

You can use the following code to do what you have in mind:

# This list will store the words that contain numbers.
words_with_numbers = []

f = open('file.txt', 'r')
for line in f:
  line = line.strip()
  words = line.split(' ')
  for w in words:
    if any(c.isdigit() for c in w):
      words_with_numbers.append(w)
f.close()

Ref: https://docs.python.org/2/library/stdtypes.html#str.isdigit

Tom
  • 918
  • 6
  • 19
Galo Castillo
  • 324
  • 3
  • 7
1

If you have a string variable you can use the str.split() function to split the data by a separator, a space by default. This will return a list of strings.

You can then iterate each item in the list and use a regular expression to select the ones that contain numbers

import re
def contains_num(inp):
    return bool(re.search(r'\d', inp)) # Search for string containing numbers

with open("symbols.txt") as f:
    symbols = f.read()

items = symbols.split()

ans = list(filter(contains_num, items))
Tom
  • 918
  • 6
  • 19
0

Here's a way:

with open("YOURFILE") as file:
    all_words = file.read().split()
    words_containing_numbers = []

    for word in all_words:
        if any(char.isdigit() for char in word):
            words_containing_numbers.append(word)
Antricks
  • 171
  • 1
  • 9
  • This is based on an answer to a similar question. Credits to thefourtheye: https://stackoverflow.com/a/19859308/12507399 – Antricks Nov 18 '20 at 17:38
  • You will need to append the word to the `words_containing_numbers` list not concatenate the word to it. – Tom Nov 18 '20 at 17:38
  • you will need append `+=` will add each character in the string as a new element in the string. – Tom Nov 18 '20 at 17:43
  • I just tested it and realized. Thanks for that ^^. Looking back it seems logical because a string is an Iterable. – Antricks Nov 18 '20 at 17:44
0

Quick one liner, just for fun, after import re:

list(filter(lambda w: re.search(r'\d', w), open("your-file.txt").read().split()))
Sumukh Barve
  • 1,414
  • 15
  • 12