Es Hauptproblem in Ihrem Code auf der Linie (Linie 9):
wordlist.append(line)
Du die ganze Zeile in die wordlist
anhängt, bezweifle ich, dass das, was man ist wollen. Wenn Sie dies tun, wird das hinzugefügte Wort nicht .strip()
ed, bevor es wordlist
hinzugefügt wird.
Was Sie tun müssen, ist das Wort hinzuzufügen erst, nachdem Sie haben strip()
es ed und stellen Sie sicher, dass Sie nur tun, nachdem Sie überprüft, dass es keine anderen gleichen Worte (keine Duplikate):
ifile = open("Story.txt",'r')
lines = ifile.readlines()
wordlist = []
countlist = []
for line in lines:
# Get all the words in the current line
words = line.split()
for word in words:
# Perform whatever manipulation to the word here
# Remove any punctuation from the word
word = word.strip(".,!?:;'\"")
# Make the word lowercase
word = word.lower()
# Add the word into wordlist only if it is not in wordlist
if word not in wordlist:
wordlist.append(word)
# Add the word to countlist so that it can be counted later
countlist.append(word)
# Sort the wordlist
wordlist.sort()
# Print the wordlist
for word in wordlist:
print(word, countlist.count(word))
Eine andere Möglichkeit, dies zu tun, ist die Verwendung eines Wörterbuchs, Speichern des Wortes als Schlüssel und die Anzahl der Vorkommen als Wert:
ifile = open("Story.txt", "r")
lines = ifile.readlines()
word_dict = {}
for line in lines:
# Get all the words in the current line
words = line.split()
for word in words:
# Perform whatever manipulation to the word here
# Remove any punctuation from the word
word = word.strip(".,!?:;'\"")
# Make the word lowercase
word = word.lower()
# Add the word to word_dict
word_dict[word] = word_dict.get(word, 0) + 1
# Create a wordlist to display the words sorted
word_list = list(word_dict.keys())
word_list.sort()
for word in word_list:
print(word, word_dict[word])
Wie möchten Sie die Wörter sortieren? alphabetisch oder nach Anzahl? – inspectorG4dget
Mögliches Duplikat von [Python - Zählen von Wörtern in einer Textdatei] (http://stackoverflow.com/questions/25778341/python-counting-words-in-a-text-file) – TessellatingHeckler