【问题标题】:Using python to search a text file for the occurence of specific characters使用 python 在文本文件中搜索特定字符的出现
【发布时间】:2013-03-13 14:54:14
【问题描述】:

我的问题与this one类似,只是我要搜索出现多个chars,例如gde,然后打印其中ALL存在指定的字符。

我尝试了以下方法,但没有成功:

searchfile = open("myFile.txt", "r")
for line in searchfile:
    if ('g' and 'd') in line: print line,
searchfile.close()

我得到的行中包含“g”或“d”或两者都有,我想要的只是两个出现,而不是至少一个,就像运行上述代码的结果一样。

【问题讨论】:

  • 你有尝试过什么吗?这并不难实现,也不需要正则表达式。

标签: python regex file search


【解决方案1】:

在模式匹配方面,正则表达式肯定会对您有所帮助,但您的搜索似乎比这更容易。请尝试以下操作:

# in_data, an array of all lines to be queried (i.e. reading a file)
in_data = [line1, line2, line3, line4]

# search each line, and return the lines which contain all your search terms
for line in in_data:
    if ('g' in line) and ('d' in line) and ('e' in line):
        print(line)

这么简单的东西应该可以工作。我在这里做一些假设: 1.搜索词的顺序无关紧要 2.大写/小写不处理 3.不考虑搜索词的频率。

希望对你有帮助。

【讨论】:

  • 哎呀,只需阅读上面的示例代码 - 并在具有预期输出的测试文件上运行它,即只返回包含两个术语的行。并意识到,如果我的样本真的和你的一样:)
  • 'g' and 'd' and 'e' in line 不起作用--相当于'e' in line;像 'g''e' 这样的非空字符串是真实的。例如,line = 'fred'; print 'g' and 'd' and 'e' in line 打印 True。
【解决方案2】:

这一行:

if ('g' and 'd') in line: 

相同
if 'd' in line:

因为

>>> 'g' and 'd'
'd'

你想要

if 'g' in line and 'd' in line:

或者,更好:

if all(char in line for char in 'gde'):

(你也可以使用集合交集,但这不太通用。)

【讨论】:

    【解决方案3】:
    if set('gd').issubset(line)
    

    这样做的好处是不会重复两次,因为c in line 的每次检查都会遍历整行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多