Reputation: 1
My goal is to make a program to use for creating flashcards and practicing language with. Right now I just want to read in a .txt file with a word and a translation, create a list from them and then print that list.
I am very much a beginner at programming.
My problem is that when it prints the list it looks like this:
att arbeta - travailler
att ga - marcher
att tala
- parler
The last word couple is always one line to low. It should look like this:
att arbeta - travailler
att ga - marcher
att tala - parler
My code:
wordList=[]
def main ():
buildList()
for i in range(len(wordList)):
print(wordList[i].returnPair())
class wordCouple():
def __init__(self, freWord, engWord):
self.freWord = freWord
self.engWord = engWord
def returnPair(self):
x = self.engWord + " - " + self.freWord
return x
def returnEng(self):
return self.engWord
def returnFre(self):
return self.freWord
def buildList():
f=open("test.txt", "r")
if f.mode == 'r':
contents =f.read()
data = contents.split("|")
for i in range(len(data)): #I think the problem is here. Here I
wordSplit = data[i].split (",")
wordList.append(wordCouple(wordSplit[0],wordSplit[1]))
else:
print("could not read text file")
main()
This is how the test.txt file that I use in the program look like.
travailler, att arbeta| marcher, att ga| parler, att tala
Upvotes: 0
Views: 56
Reputation: 61643
When you read in the line of data, it has a newline character at the end; when you .split()
that result, the last of those sections (here, parler, att tala
) still has that newline at the end; and thus when you split it again, you still have the newline on att tala
(and also the leading space).
Use the .strip()
method of strings to remove leading and trailing whitespace - it produces a new string (strings cannot be modified in-place).
But while I have your attention:
for i in range(len(wordList)):
print(wordList[i].returnPair())
Do not do this; if someone taught you to do this, do not listen to that person or source again; and if you came up with it yourself, then review your understanding and reasoning. In Python, for
loops already give you the contents of your underlying iterable (here, wordList
) directly; with code like this you are going out of your way to make things harder for yourself. What you want is instead:
for word in wordList:
print(word.returnPair())
That is: you directly ask for each word
and use it - instead of asking for how many words there are, and then figuring out all the numbers from 0 up to that count (non-inclusive), and then asking for those numbers individually, and finally using the numbers to grab the words. Simple :)
Upvotes: 1