繁体   English   中英

使用python在文本文件中搜索特定字符的出现

[英]Using python to search a text file for the occurence of specific characters

我的问题类似于问题,除了我想搜索多个chars (例如gde ,然后打印其中所有指定字符都存在的行。

我尝试了以下方法,但是没有用:

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

我得到的行中都带有'g'或'd'或两者都有,我想要的只是两种情况,而不是至少一种情况,这是运行上述代码的结果。

if set('gd').issubset(line)

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

这行:

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'):

(您也可以使用集合交集,但是通用性较低。)

正则表达式无疑会在模式匹配方面为您提供帮助,但是看起来您的搜索要比这容易。 请尝试以下操作:

# 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.不考虑搜索词的出现频率。

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM