1

I am currently trying to compare to text files, to see if they have any words in common in both files.

The text files are as

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

My current code is getting them to print, Ive removed all the unnessecary squirly brackets and so on, but I cant get them to print on different lines.

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)

The output is expected to separate both results onto new lines.

Currently Happening: 
Competition Table
Expected:
Competition
Table

Thanks in advance! - Xphoon

Xphoon
  • 21
  • 3

1 Answers1

0

Hi I'd suggest you to try two things as a good practice: 1) Use "with" for opening files

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

2) Try to use the "f-String" opportunity if you're using Python 3:

print(f"Hello\nWorld!")

File read using "open()" vs "with open()" This post explains very well why to use the "with" statement :) And additionally to the f-strings if you want to print out variables do it like this:

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

Should print out: Hello and World! in seperate lines

Here is one solution including converting between sets and lists:

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)

Here is another solution by keeping the words in lists:

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)
newbiedude
  • 51
  • 1
  • 5