简体   繁体   English

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

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

My question is similar to this one , except that I want to search for the occurrence of multiple chars , for example g , d and e , and then print the line in which ALL the specified characters exist. 我的问题类似于问题,除了我想搜索多个chars (例如gde ,然后打印其中所有指定字符都存在的行。

I have tried the following but it didn't work: 我尝试了以下方法,但是没有用:

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

I was getting lines which had EITHER 'g' or 'd' or both in them, all I want is just both occurences, not at least one of them, as is the result of running the above code. 我得到的行中都带有'g'或'd'或两者都有,我想要的只是两种情况,而不是至少一种情况,这是运行上述代码的结果。

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

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

This line: 这行:

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

is the same as 是相同的

if 'd' in line:

because 因为

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

You want 你要

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

or, better: 或更好:

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

(You could use set intersection too, but that's less generalizable.) (您也可以使用集合交集,但是通用性较低。)

regular expressions will certainly help you when it comes to pattern matching, but it seem s that your search is easier than this. 正则表达式无疑会在模式匹配方面为您提供帮助,但是看起来您的搜索要比这容易。 Try the following: 请尝试以下操作:

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

Something this simple should work. 这个简单的东西应该可以工作。 I am making a few assumptions here: 1. the order of the search terms does not matter 2. upper / lower case is not dealt with 3. the frequency of the search terms is not considered. 我在这里做出一些假设:1.搜索词的顺序无关紧要; 2.不处理大写/小写字母; 3.不考虑搜索词的出现频率。

Hope it helps. 希望能帮助到你。

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

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