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

时间:2016-01-04 12:16:07

标签: python string

脚本的第一部分是正常的(它删除了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

2 个答案:

答案 0 :(得分:4)

这样的事情应该有效:

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)

答案 1 :(得分:3)

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

>>> 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]

如果你愿意的话。