将结果从集合转换为字符串后,如何在单独的行上打印结果?

时间:2019-02-08 22:19:01

标签: python-3.x

我目前正在尝试与文本文件进行比较,以查看两个文件中是否有共同的词。

文本文件为

ENGLISH.TXT
circle
table
year
competition
FRENCH.TXT
bien
competition
merci
air
table

我当前的代码是让它们打印,我已经删除了所有不必要的方括号等,但是我无法让它们在不同的行上打印。

List = open("english.txt").readlines()
List2 = open("french.txt").readlines()

anb = set(List) & set(List2)
anb = str(anb)

anb = (str(anb)[1:-1])
anb = anb.replace("'","")
anb = anb.replace(",","")
anb = anb.replace('\\n',"")

print(anb)

预计输出将把这两个结果分隔到新行中。

Currently Happening: 
Competition Table
Expected:
Competition
Table

提前谢谢! -Xphoon

1 个答案:

答案 0 :(得分:0)

嗨,我建议您尝试以下两种做法,作为一种好的做法: 1)使用“ with”打开文件

with open('english.txt', 'r') as englishfile, open('french.txt', 'r') as frenchfile:
##your python operations for the file

2)如果您使用的是Python 3,请尝试使用“ f-String”机会:

print(f"Hello\nWorld!")

File read using "open()" vs "with open()" 这篇文章很好地解释了为什么要使用“ with”语句:) 另外,如果要打印出变量,请在f字符串之外执行以下操作:

 print(f"{variable[index]}\n variable2[index2]}")

应打印出: 你好,世界!在单独的行中

这是一种包括在集合和列表之间进行转换的解决方案:

with open('english.txt', 'r') as englishfile, open('french.txt', 'r') as frenchfile:

   english_words = englishfile.readlines()
   english_words = [word.strip('\n') for word in english_words]
   french_words = frenchfile.readlines()
   french_words = [word.strip('\n') for word in french_words]

   anb = set(english_words) & set(french_words)
   anb_list = [item for item in anb]
   for item in anb_list:
       print(item)

这是将单词保留在列表中的另一种解决方案:

with open('english.txt', 'r') as englishfile, open('french.txt', 'r') as frenchfile:

   english_words = englishfile.readlines()
   english_words = [word.strip('\n') for word in english_words]
   french_words = frenchfile.readlines()
   french_words = [word.strip('\n') for word in french_words]

   for english_word in english_words:
       for french_word in french_words:
           if english_word == french_word:
               print(english_word)