[英]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
. 例如,如果文件包含
:raining, raining:, rai:ning
,则仅删除: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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.