【问题标题】:Read line in file, print line if it contains string读取文件中的行,如果它包含字符串则打印行
【发布时间】:2015-11-11 18:54:05
【问题描述】:

我有一个工作代码,可以打开一个文件,查找一个字符串,如果它包含该字符串,则打印该行。我这样做是为了手动决定是否应该从我的数据集中删除该行。

但是如果我可以告诉程序读取包含两个逗号之间的字符串的那部分行会更好。

我现在拥有的代码(见下文)

with open("dvd.txt") as f:
    for num, line in enumerate(f, 1):
        if " arnold " in line:
            num = str(num)
            print line + '' + num

像这样打印每一行:

77.224998664,2014-10-19,386.5889,the best arnold ***** ,81,dvd-action,Cheese 5gr,online-dvd-king93,0.19976,18,/media/removable/backup/2014-10-19/all_items/cheese-5gr?feedback_page=1.html,    ships from: Germany    ships to: Worldwide  ,2014-07-30,online-dvd-king,93 1

我希望它打印出来:

,the best arnold ***** , 1

the best arnold *****  1

我阅读了this 的问题,但我希望避免使用 CSV。

如果由于某种原因难以找到逗号或任何其他特定字符之间的文本,则在我要查找的字符串之前和之后打印 3 个单词会很有用。

【问题讨论】:

  • 为什么不想使用 CSV 模块来解析 CSV?
  • 我需要的文件并不总是 CSV 或类似的电子表格
  • 那么,这太宽泛了。在“这个字符串中有这个词”和“只打印这个字符串中的某些词”之间有很多步骤。特别是因为您实际上并没有向我们展示您正在使用的格式。
  • 文件多为txt文件,以行分隔

标签: python python-2.7 text


【解决方案1】:

使用str.split() 非常简单。如下修改您的函数将产生您想要的输出。

with open("dvd.csv") as f:
    for num, line in enumerate(f, 1):
        if " arnold " in line:
            num = str(num)
            print line.split(',')[3] + '' + num 

str.split 通过指定的分隔符将字符串拆分为列表。要访问您想要的列表条目,只需提供适当的索引(在您的情况下应该是 3)。

顺便说一句,您可以使用str.format() 方法生成您的输出,让它更好一点:

print "{} {}".format(line.split(',')[3], num)

这也将允许您删除num = str(num),因为格式方法可以处理多种数据类型(与不能处理的字符串连接相反)。

【讨论】:

    【解决方案2】:

    作为替代方案,您可以使用如下正则表达式:

    with open("dvd.txt") as f:
        for num, line in enumerate(f, 1):
            re_arnold = re.search(r',\s*([^,]*?arnold[^,]*?)\s*,', line)
    
            if re_arnold:
                print '{} {}'.format(re_arnold.group(1), num)
    

    这将提取整个条目(在逗号之间),而不管它在哪个字段中。

    【讨论】:

    • 如果搜索键在哪个条目(在哪个逗号之间)有所不同,这绝对是更好的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 2013-05-01
    相关资源
    最近更新 更多