1

我希望我的 python 程序在文本文件中搜索字符串的特定部分。例如,我的文本文件如下所示:

VERSION_1_0001
VERSION_2_0012
VERSION_3_0391

这些只是例子。我希望我的 python 程序查找“VERSION_2_”,但让它在另一个文本文件中打印出 0012。那可能吗?

到目前为止,我只有这个:

with open('versions.txt', 'r') as verFile:
    for line in verFile:
        if 'VERSION_2_' in line:
            ??? (I don't know what would go here so I can get the portion attached to the string I'm finding)

我在这里先向您的帮助表示感谢!

4

1 回答 1

3

如果您的问题是关于如何提取最后一个下划线之后的行部分:

 with open('versions.txt', 'r') as verFile:
    for line in verFile:
        if 'VERSION_2_' in line:
            # Split the line from the right on underscores and
            # take the last part of the resulting list.
            print line.rpartition('_')[-1]

如果您的问题是关于写入文件:

with open('resultfile', 'w') as wFile:
    wFile.write(line.rpartition('_')[-1])

如果要将所有结果写入同一个文件,请在循环外打开要写入的文件:

# It doesn't matter which `with` block is the outermost.
with open('resultfile', 'w') as wFile:
    with open('versions.txt', 'r') as verFile:
        for line in verFile:
            if 'VERSION_2_' in line:
                # Split the line from the right on underscores and
                # take the last part of the resulting list.
                wFile.write(line.rpartition('_')[-1])
于 2013-04-08T19:21:05.283 回答