【问题标题】:Search for specific string, only copy part of string into another textfile搜索特定字符串,仅将部分字符串复制到另一个文本文件中
【发布时间】:2013-03-31 00:13:27
【问题描述】:

我希望我的 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)

提前感谢您的帮助!

【问题讨论】:

  • 你真的要检查'VERSION_2_' in line而不是line.startswith('VERSION_2_')吗?
  • 我宁愿签入行,因为在某些文本文件中,实际 VERSION 之前有各种字符。所以它可能并不总是以 VERSION 开头。
  • 好的,您肯定已经了解您的数据,深思熟虑,并做出了正确的决定。酷。

标签: python string file search


【解决方案1】:

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

 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])

【讨论】:

  • +1。但是您实际上并不需要在这里将2 作为maxsplit 传递。你只想要最右边的值,所以你可以传递1。或者,为简单起见,将其关闭。
  • @abarnert 哦,我知道,我只是假设拆分越少越好。 ;)
  • @kojiro:如果拆分越少越好,请使用1 而不是2(或使用rpartition 而不是rsplit)。
  • @chakolatemilk 拆分量是您不需要担心的微优化。基本上,我们试图减少 Python 在刚刚被丢弃的数据上花费的精力。正如 abarnert 所说,使用 rpartition。 (我已经编辑了我的答案。)
  • @chakolatemilk:学习这些东西的最好方法是在交互式终端中尝试。写s='VERSION_2_0012',然后看看s.rsplit('_', 2)s.rsplit('_', 1)s.rsplit('_')和s.rpartition('_')`打印出来的内容。然后,如果不是很明显,请尝试在每个后面加上[-1]。或者用s='extra_stuff VERSION_2_0012'等试试。继续试验直到你理解为止。
猜你喜欢
  • 2016-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-05
  • 2014-05-26
  • 2013-06-25
相关资源
最近更新 更多