【问题标题】:how to filter a txt file with specific strings如何过滤带有特定字符串的txt文件
【发布时间】:2018-04-30 22:22:27
【问题描述】:

我有一个文件 (file1.txt),其中第一列包含字符串,我想在另一个文件 (file2.txt) 中过滤其字符串与列表“indref”完全对应的行(参见代码)。问题是生成的文件(参见简短示例)还附加了那些以我要附加的值“开始”的字符串。我只想附加特定的字符串('indref' 中的那些)。谢谢。

import numpy as np

indref = ['p1', 'p3']

with open('file1.txt') as oldfile, open('file2.txt', 'w') as newfile:

    for line in oldfile:
        if any(x in line for x in indref):
            newfile.write(line)

file1.txt 示例

p1        4.252613E+01  
p2        4.245285E+01  
p3        4.272667E+01 
p4        4.255809E+01  
p5        4.284104E+01  
p6        4.292802E+01  
p7        4.295814E+01  
p8        4.286242E+01  
p9        4.286862E+01  
p10       4.258108E+01  

file2.txt:

p1        4.252613E+01  
p3        4.272667E+01 
p10       4.258108E+01  

【问题讨论】:

  • 为什么包含p10?它似乎不在您的indref 列表中
  • 在 'p1' 之后添加空格或制表符 '\t'(取决于文件中的内容)或使用正则表达式
  • @chrisz 这就是问题所在。

标签: python string filter


【解决方案1】:

使用split 得到了很好的答案,但可以精简到

indref = ['p1', 'p3']

with open('file1.txt') as oldfile, open('file2.txt', 'w') as newfile:
    newfile.writelines(line for line in oldfile if line.split()[0] in indref)

【讨论】:

    【解决方案2】:

    可以在每一行使用split(),然后检查第一个元素是否在indref中:

    with open('test.txt') as f:
      indref = {'p1', 'p3'}
      data = [i for i in f.read().splitlines() if i.split()[0] in indref]
    
      with open('test2.txt', 'w') as f:
        f.write('\n'.join(data))
    

    输出:

    p1        4.252613E+01  
    p3        4.272667E+01 
    

    我将 indref 更改为一个集合,因为在集合中查找的平均时间为 O(1),如果它是一个非常大的列表查找可能会很昂贵。

    【讨论】:

    • 这行得通,但是从原始的逐行实现更改为读取整个文件并拆分的实现很奇怪。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多