Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何基于数组元素检查文本文件中是否存在字符串?_Python_Arrays_Loops - Fatal编程技术网

Python 如何基于数组元素检查文本文件中是否存在字符串?

Python 如何基于数组元素检查文本文件中是否存在字符串?,python,arrays,loops,Python,Arrays,Loops,我有一个包含字符串的数组。 我有一个文本文件。 我想逐行遍历文本文件。 并检查数组中的每个元素是否存在。 (它们必须是完整的单词,而不是子字符串) 我被卡住了,因为我的脚本只检查第一个数组元素是否存在。 但是,我希望它返回每个数组元素的结果,并注意该数组元素是否存在于整个文件中 #!/usr/bin/python with open("/home/all_genera.txt") as file: generaA=[] for line in file:

我有一个包含字符串的数组。 我有一个文本文件。 我想逐行遍历文本文件。 并检查数组中的每个元素是否存在。 (它们必须是完整的单词,而不是子字符串) 我被卡住了,因为我的脚本只检查第一个数组元素是否存在。 但是,我希望它返回每个数组元素的结果,并注意该数组元素是否存在于整个文件中

#!/usr/bin/python



with open("/home/all_genera.txt") as file:

    generaA=[]

    for line in file:
        line=line.strip('\n')
        generaA.append(line)


with open("/home/config/config2.cnf") as config_file:
    counter = 0
    for line in config_file:
        line=line.strip('\n')

        for part in line .split():
            if generaA[counter]in part:
                print (generaA[counter], "is -----> PRESENT")
            else:
                continue
    counter += 1

计数器没有增加,因为它在
for
循环之外

with open("/home/all_genera.txt") as myfile: # don't use 'file' as variable, is a reserved word! use myfile instead

    generaA=[]

    for line in myfile: # use .readlines() if you want a list of lines!
        generaA.append(line)

# if you just need to know if string are present in your file, you can use .read():
with open("/home/config/config2.cnf") as config_file:
    mytext = config_file.read()
    for mystring in generaA:
        if mystring in mytext:
            print mystring, "is -----> PRESENT"

# if you want to check if your string in line N is present in your file in the same line, you can go with:
with open("/home/config/config2.cnf") as config_file:
    for N, line in enumerate(config):
        if generaA[N] in line:
            print "{0} is -----> PRESENT in line {1}".format(generaA[N], N)
我希望一切都清楚


这段代码可以在许多方面得到改进,但我尝试让它与您的代码类似,以便更容易理解

如果我理解正确,您需要两个文件中的单词序列。如果是,
set
是您的朋友:

def parse(f):
    return set(word for line in f for word in line.strip().split())

with open("path/to/genera/file") as f:
    source = parse(f)
with open("path/to/conf/file" as f:
    conf = parse(f)

# elements that are common to both sets
common = conf & source
print(common)

# elements that are in `source` but not in `conf`
print(source - conf)

# elements that are in `conf` but not in `source`
print(conf - source)
因此,要回答“我希望它返回每个数组元素的结果,并说明该数组元素是否存在于整个文件中”,您可以使用公共元素或
source-conf
差异来注释
source
列表:

# using common elements
common = conf & source
result = [(word, word in common) for word in source]
print(result)

# using difference
diff = source - conf
result = [(word, word not in diff) for word in source]
两者都会得到相同的结果,而且由于集合查找是O(1),性能也应该相似,因此我建议第一种解决方案(积极的断言比消极的断言更容易让大脑接受)

当然,在构建集合时,您可以应用进一步的清理/规范化,即如果您想要不区分大小写的搜索:

def parse(f):
    return set(word.lower() for line in f for word in line.strip().split())

“您根本没有读取文件。”=>完全错误。“如果需要行列表,请使用.readlines()”=>无需,文件是可编辑的。您的代码只会将用于读取文件的内存增加一倍,这是没有充分理由的。如果任何文件包含非英语单词,该怎么办?除了ascii,还有很多其他的字母你知道吗?当然。。。这就是为什么规范化的文本是它自己的东西。。。由用户指定他们感兴趣的字母表中的文本规范化所需的内容这是一个理想的想法,但当我尝试时,它抱怨无法使用正则表达式计算位(或数组元素)
TypeError:无法在像object这样的字节上使用字符串模式
try
re.sub(b“[^a-z0-9]”····················································,Python具有大多数常用功能,因此您可以使用常用的蛮力样式(列表上的嵌套循环等)进行操作。但是它也有很多很好的特性和丰富的内置类型,当你知道它们的存在和使用它们时,你的生活会变得更轻松。大多数时候,当您发现自己在用Python编写“暴力”风格的代码时,您应该停下来问问自己“哪种内置数据类型可以以更干净的方式解决这个问题”。使用正确的数据类型是编写好代码的关键。是的,我越来越发现这一点。谢谢
def parse(f):
    return set(word.lower() for line in f for word in line.strip().split())