简体   繁体   中英

Python Regex - remove words containing “:” from file

I have code that will remove a string from a file if the string contains : at the start of the string.

with open("test1.txt") as the_file:
    for each_line in the_file:
        each_line = " ".join(filter(lambda x:x[0]!=':', each_line.split()))
        print(each_line)

What is the correct expression to remove the string if it contains : anywhere in the string?

For example if the file contains :raining, raining:, rai:ning , It will only remove :raining . I want to remove all of these words from the file.

with open('test.txt', 'r') as f:
    for line in f.readlines():
        if ':' in line:
            # Remove
        else:
            # Keep

This might help. Removes all string which has ":" in it.

a = ":raining, raining:, rai:ning  aaaaaaa"
def removeStr(val):
    if ":" not in val:
        return val

each_line = " ".join(filter(removeStr, a.split()))
print each_line

Output:

aaaaaaa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM