共同的词(Python)

时间:2018-05-23 04:43:13

标签: python

所以我在这个问题上遇到了很多麻烦。我必须从English.txt和French.txt中找到共同的词。

english.txt:

circle
table
year
competition

french.txt:

bien
competition
merci
air
table

我想要的输出:

competition
table

然而,当我完成我的代码时,我没有包含法语文本但得到了: 竞争

这是我的代码:

filenameI = "english.txt"
file = open(filenameI, "r")
for line in file:
   print(line)

6 个答案:

答案 0 :(得分:0)

with open(filenameI) as I:
    contentI = I.read().splitlines()

with open(filenameF) as F:
    contentF = F.read().splitlines()

然后继续循环遍历contentF和contentI并比较两者,匹配时打印

for i in contentI:
    for f in contentf:
        if i == f:
          print(i)

希望有帮助:)

答案 1 :(得分:0)

试试这个:

filenameI = "english.txt"
filename2 = "french.txt"
file = open(filenameI, "r")
file2 = open(filenameI, "r")

list1 = [line for line in file]
list2 = [line for line in file2]

out = set(list1) - (set(list1) - set(list2))

请注意,最好使用with打开文件。

答案 2 :(得分:0)

请告诉我这是否适合您!

e_words = set(line.strip() for line in open("english.txt")) # speck of sanity check here
f_words = set(line.strip() for line in open("french.txt"))

print e_words & f_words
# please iterate this and do whatevs..

编辑1(虽然很好但是这个时候没有文件处理程序)

output = None
with open("english.txt") as e, open("french.txt") as f:
     output = set([line.strip() for line in e.readlines()]) & set([line.strip() for line in f.readlines()])
print output

答案 3 :(得分:0)

使用set,因为它会为您提供两个集合之间的交集。

还可以使用with来自动关闭文件。

with open('english.txt') as eng, open('french.txt') as fr:
    print(set(x.strip() for x in eng).intersection(x.strip() for x in set(fr)))

输出:

{'table', 'competition'}

答案 4 :(得分:0)

试试这个:

file1 = open("english.txt", "rb+")
file2 = open("french.txt", "rb+")

list1 = [line for line in file1]
list2 = [line for line in file2]

common1 = (set(list1).intersection(list2))

答案 5 :(得分:0)

这是我的答案:

e = set(open("english.txt"))
f = set(open("french.txt"))
for c in e & f:
print(c, end="")

我只从两本书中选出两套。然后使用一个循环,在该循环中,对于每个常见单词(使用“ e&f”),它们会在每行中列出它们。

p.s。

end=""

只要确保每个单词之间没有多余的行即可。