Remove unmixed numbers from a file

Let's say I have a file called input.txt that looks like

I listened to 4 u2 albums today
meet me at 5
squad 4ever

I want to filter out numbers that are on their own, so "4" and "5" should go, but "u2" and "4ever" should remain unchanged. the conclusion should be

I listened to u2 albums today
meet me at
squad 4ever

I tried to use this code

for line in fileinput.input("input.txt", inplace=True):
    new_s = ""
    for word in line.split(' '):
        if not all(char.isdigit() for char in word):
            new_s += word
            new_s += ' '
    print(new_s, end='')

Which is very similar to the code I found here: Removing numbers mixed with letters from a string

But instead of the desired output, I get

I listened to u2 albums today
 meet me at 5
 squad 4ever 

As you can see, there are two problems: first, only the first line loses the number I want to lose, "5" is still present in the second line. The second problem is an extra space at the beginning of a new line.

stackoverflow, , . - ?

+4
3

str.split(' ') . . '5' , '5\n', \n .

. , , . .

- line.split(' ') line.split(). - split() , . end='' print, .

+3

regexp.

re.sub(r"\b\d+\b", "", input)

, :

re.sub(r"\s\d+\s", " ", input)
+1

You can use regex:

data = open('file.txt').read()
import re
data = re.sub('(?<=\s)\d+(?=$)|(?<=^)\d+(?<=\s)|(\s\d+\s)', '', data)

Conclusion:

I listened tou2 albums today
meet me at
squad 4ever
0
source

Source: https://habr.com/ru/post/1689320/


All Articles