我需要在数据文件中搜索一个字符串。但字符串写在另一个文件中

时间:2018-01-17 06:24:14

标签: python file

我要在一个文件中搜索关键词,比如说abc.txt,在另一个文件中我有我的数据def.txt。 我希望python中的代码能够在def.txt中找到用abc.txt编写的关键字,如果存在,则在新文件中打印这些行。 谢谢。 我尝试编写代码但它没有用。 以下是我写的代码。

f = open('/home/vivek/Documents/abc.txt')
f1 = open('output.txt', 'a')
f2 = open('/home/vivek/Documents/def.txt', 'r')

# doIHaveToCopyTheLine=False

for line in f.readlines():
      if f2 in line:
        f1.write(line)

f1.close()
f.close()
f2.close()

4 个答案:

答案 0 :(得分:1)

将关键字加载到列表中,然后您可以逐行检查其他文件,并在行中找到关键字时写入outfile

with open('/path/to/keywords.txt') as f:
    keywords = set(line.strip() for line in f) # assuming words are separated by line

with open('/path/to/search_me.txt') as f, open('/path/to/outfile.txt', 'w') as outfile:
    for line in f:
        if any(kw in line for kw in keywords):
            outfile.write(line)

答案 1 :(得分:0)

你应该记录abc.txt中的所有单词使用一个集合,然后在def.txt中搜索它们

word_set = set()
with open('/home/vivek/Documents/abc.txt') as f:
    for line in f:
        word_set.add(line.strip())
f1 = open('output.txt', 'a')
with open('/home/vivek/Documents/def.txt') as f:
    for line in f:
        find = False
        for word in word_set:
            if word in line:
                find = True
                break
        if find:
            f1.write(line)
f1.close() 

答案 2 :(得分:0)

您可以尝试以下代码:

with open("keyword.txt", "r") as keyword_file:
    keywords = keyword_file.read().strip()
    keywords = keywords.split()

with open("data.txt", "r") as data_file, open("output.txt", "w") as output_file:
    for line in data_file.readlines():
        line = line.strip()
        for word in keywords:
            if line.find(word) != -1:
                print line
                output_file.writelines(line + '\n')
                break

答案 3 :(得分:0)

除了sytech的答案,你可以试试这个:

with open('def.txt') as kw_obj, open('abc.txt') as in_obj:
    keywords = set(kw_obj.read().split())
    in_lines = in_obj.readlines()
    match_lines = [line for keyword in keywords for line in in_lines if keyword in line]

if match_lines:
    with open('out.txt', 'w') as out:
        out.write(''.join(match_lines))