How do I print out results on a separate line after converting them from a set to a string?
我目前正在尝试与文本文件进行比较,以查看两个文件中是否有共同的单词。
文本文件如下
1 2 3 4 5 | ENGLISH.TXT circle table year competition |
1 2 3 4 5 6 | FRENCH.TXT bien competition merci air table |
号
我目前的代码是让他们打印,我删除了所有不必要的斜线括号等,但我不能让他们打印在不同的行。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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('\ ',"") print(anb) |
预期输出将两个结果分离到新的行中。
1 2 | Currently Happening: Competition Table |
。
1 2 3 | Expected: Competition Table |
事先谢谢!-爆竹
嗨,我建议你尝试两件事作为一个好的实践:1)使用"with"打开文件
1 2 | with open('english.txt', 'r') as englishfile, open('french.txt', 'r') as frenchfile: ##your python operations for the file |
2)如果您使用的是python 3,请尝试使用"f-string"机会:
1 2 | print(f"Hello World!") |
号
使用"open()"vs"with open()"读取文件这篇文章很好地解释了为什么要使用"with"语句:)另外,对于F字符串,如果您想打印出变量,请这样做:
1 2 | print(f"{variable[index]} variable2[index2]}") |
应该打印出来:你好,全世界!在单独的行中
这里有一个解决方案,包括在集合和列表之间转换:
1 2 3 4 5 6 7 8 9 10 11 12 13 | with open('english.txt', 'r') as englishfile, open('french.txt', 'r') as frenchfile: english_words = englishfile.readlines() english_words = [word.strip(' ') for word in english_words] french_words = frenchfile.readlines() french_words = [word.strip(' ') 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) |
。
下面是另一个解决方案,将单词保留在列表中:
1 2 3 4 5 6 7 8 9 10 11 12 13 | with open('english.txt', 'r') as englishfile, open('french.txt', 'r') as frenchfile: english_words = englishfile.readlines() english_words = [word.strip(' ') for word in english_words] french_words = frenchfile.readlines() french_words = [word.strip(' ') 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) |