无法用variab替换字符串

2024-10-01 22:43:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想出了下面的方法,在一行中找到一个字符串,并将该行复制到一个新文件中。我想用更动态的东西来替换Foo23(例如[0-9],等等),但是我不能让这个或者变量或者regex工作。它没有失败,但我也没有结果。救命啊?谢谢。你知道吗

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)

Tags: 文件csvtopath方法字符串inas
2条回答

根据您的注释,每当出现任何三个字母后跟两个数字时,您都希望匹配行,例如foo12bar54。使用正则表达式!你知道吗

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

本质上,您的问题归结为:“我想确定字符串是否与模式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外部的过滤。一般来说,为了便于测试和维护,代码的每一部分都应该做“一件事”。你知道吗

相关问题 更多 >

    热门问题