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.

2
  • split the string by space, and filter by the names with numbers in Commented Nov 18, 2020 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. Commented Nov 18, 2020 at 17:40

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Using break after .append(w) should reduce the number of characters checked.
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))

Comments

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)

4 Comments

This is based on an answer to a similar question. Credits to thefourtheye: stackoverflow.com/a/19859308/12507399
You will need to append the word to the words_containing_numbers list not concatenate the word to it.
you will need append += will add each character in the string as a new element in the string.
I just tested it and realized. Thanks for that ^^. Looking back it seems logical because a string is an Iterable.
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()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.