繁体   English   中英

如何在两个文本文件中查找单词

[英]How to find words inside two text files

脚本的第一部分是OK(它删除了http://www. )。 后来我需要检查源内的单词是否存在。

source = open('/net/sign/temp/python_tmp/script1/source.txt','r')
exists = open('/net/sign/temp/python_tmp/script1/exists.txt','r')

with source as f:
        lines = f.read()
        lines = lines.replace('http://','')
        lines = lines.replace('www.','')

        for a in open('/net/sign/temp/python_tmp/script1/exists.txt'):
            if a == lines:
                print("ok")

source.txt的内容:

www.yahoo.it
www.yahoo.com
www.google.com
http://www.libero.it

exists.txt的内容:

www.yahoo.com

这样的事情应该有效:

source_words = set()
with open('source.txt') as source:
    for word in source.readlines():
        source_words.add(word.replace('http://','').replace('www.','').strip())

exist_words = set()
with open('exist.txt') as exist:
    for word in exist.readlines():
        exist_words.add(word.replace('http://','').replace('www.','').strip())

print("There {} words from 'source.txt' in 'exists.txt'".format(
   "are" if exist_words.intersection(source_words) else "aren't"
))

如果您需要获取两个文件中存在的确切单词,则它们位于交集结果中:

print("These words are in both files:")
for word in exist_words.intersection(source_words):
    print(word)

好的,从您的示例文件判断您实际要做的是查找两个文本文件共享的行。 如果您的文件不是巨大的,一个简单的解决方案是读取文件并计算它们的行集的交集。

>>> with open('source.txt') as s, open('exists.txt') as e:
...     result = set(s).intersection(e)
... 
>>> result
set(['www.yahoo.com\n'])

您可以替换'http://''www.' 之后用

result = [x.replace('http://', '').replace('www.', '') for x in result]

如果你想。

暂无
暂无

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

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