Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.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:从文件n1中提取一个关键字,并在文件n2中搜索该关键字_Python - Fatal编程技术网

Python:从文件n1中提取一个关键字,并在文件n2中搜索该关键字

Python:从文件n1中提取一个关键字,并在文件n2中搜索该关键字,python,Python,我正在写一个简单的代码,但这个代码不起作用 Python代码: f = open("webfile.txt", "r") data = open("data.txt", "r") char = "(" count = 0 for x in f: partitioned_string = x.rpartition(char) key = partitioned_string[0]

我正在写一个简单的代码,但这个代码不起作用

Python代码:

f = open("webfile.txt", "r")
data = open("data.txt", "r")
char = "("
count = 0

for x in f:
    partitioned_string = x.rpartition(char)
    key = partitioned_string[0]

    for y in data:
        count += 1

        if key in str(y):
            print(f"found: {key}")

print(count)
在这个例子中,我只是在char“(“从文件webfile.txt,我把这个字符串放在名为“key”的变量中,我在文件data.txt中查找这个字符串,如果它找到了,我就有输出“find:key”.File webfile.txt大约有1K行,data.txt大约有20K行,这就是我需要创建脚本的原因。在这一行:
如果在str(y)中输入key:
如果我用“大象”替换key,例如,它可以工作,但是如果“大象”变量键中没有,找不到。没有错误消息,只是找不到。我还使用
print(key)
检查了输出,结果是正确的,我不明白为什么使用变量找不到,有什么建议吗?非常感谢

雷纳托


我可以自己找到解决方案,第二个文件必须在第一个文件中打开:

f = open("testing.txt", "r")
char = "("
count = 0

for x in f:
    partitioned_string = x.rpartition(char)
    key = partitioned_string[0]
    data = open("testing2.txt", "r")
    for y in data:
        if key in y:
            count += 1
            print(f"found: {key}")

print(count)

看起来您的代码应该可以工作。包含
elephant
的变量
key
和用文本字符串
elephant
替换
key
之间应该没有区别。您的代码或数据中一定有其他错误。@RokKlancar说:我试图重现这个问题在我的电脑上,通过复制你的代码和创建简单的.txt文件。但是一切都很好。if语句接收关键变量并找到字符串。你能提供一个有意义的示例,你的webfile.txt和data.txt吗?创建两个小数据文件来重现行为可能会帮助你自己解决这个问题使用更简单的数据。如果没有,那么你可以在你的问题中发布这两个文件,你可以得到帮助来确定哪里出了问题。事实上,你的代码似乎没有问题,因此我不知道其他人能做些什么来帮助我。我可以自己找到解决方案。问题是第二个文件必须在第一个文件内部打开,而不是外部。我要在我的问题下添加解决方案。感谢大家的帮助!@Renato关闭您打开的文件是一个很好的做法-->data.close()和f.close()