我想出了下面的方法,它在一行中查找一个字符串,并将该行复制到一个新文件中。我想用更动态的东西(如0-9等)替换Foo23
,但我不能让它、变量或正则表达式工作。它不会失败,但我也没有得到任何结果。帮助?谢谢。
with open('C:/path/to/file/input.csv') as f:
with open('C:/path/to/file/output.csv', "w") as f1:
for line in f:
if "Foo23" in line:
f1.write(line)
发布于 2018-07-25 02:31:12
根据您的注释,只要出现三个字母后跟两个数字,例如foo12
和bar54
,您就希望匹配各行。使用正则表达式!
import re
pattern = r'([a-zA-Z]{3}\d{2})\b'
for line in f:
if re.findall(pattern, line):
f1.write(line)
这将匹配像'some line foo12'
和'another foo54 line'
这样的行,但不匹配'a third line foo'
或'something bar123'
。
将其分解:
pattern = r'( # start capture group, not needed here, but nice if you want the actual match back
[a-zA-Z]{3} # any three letters in a row, any case
\d{2} # any two digits
) # end capture group
\b # any word break (white space or end of line)
'
如果您真正需要的只是将文件中的所有匹配项写入f1
,则可以使用:
matches = re.findall(pattern, f.read()) # finds all matches in f
f1.write('\n'.join(matches)) # writes each match to a new line in f1
发布于 2018-07-25 02:58:31
本质上,您的问题可以归结为:“我想确定字符串是否与模式X匹配,如果匹配,则将其输出到文件”。完成此操作的最好方法是使用reg-ex。在Python中,标准的reg-ex库是re
。所以,
import re
matches = re.findall(r'([a-zA-Z]{3}\d{2})', line)
将这一点与文件IO操作结合起来,我们可以:
data = []
with open('C:/path/to/file/input.csv', 'r') as f:
data = list(f)
data = [ x for x in data if re.findall(r'([a-zA-Z]{3}\d{2})\b', line) ]
with open('C:/path/to/file/output.csv', 'w') as f1:
for line in data:
f1.write(line)
请注意,我拆分了您的文件IO操作,以减少嵌套。我还删除了IO之外的过滤。一般来说,为了便于测试和维护,代码的每个部分都应该做“一件事”。
https://stackoverflow.com/questions/51505207
复制相似问题