【发布时间】:2015-06-19 22:49:51
【问题描述】:
我从这里 (https://sourceforge.net/project/showfiles.php?group_id=128318&package_id=141110) 下载了一本包含所有意大利语单词的字典。我想将它们添加到列表中,以便可以使用 randint(0, list.count()) 将随机意大利语单词用作字符串。 小程序基本上就是“猜字”。 我使用了本指南:Creating a list of every word from a text file without spaces, punctuation 来查看我可以做些什么来实现这一点,但我收到了 ascii 代码错误。然后我尝试用有效字符 (àèèìù) 替换奇数字符 (‡ËÈÏÚ),并删除了 thesaurus.txt 文件的第一行,但我仍然得到相同的 ascii 错误。 提前感谢您的帮助,我是 Python 的新手。 哦,这是代码,这样您就可以重新创建 ascii 错误(您可以从上面的链接下载 .txt 文件)。
import re
from random import *
file = open('thesaurus.txt', 'r')
# .lower() returns a version with all upper case characters replaced with lower case characters.
text = file.read().lower()
file.close()
# replaces anything that is not a lowercase letter, a space, or an apostrophe with a space:
text = re.sub('[^a-z\ \']+', " ", text)
words = list(text.split())
word = random.choice(words)
wordlist = list(word)
guess = []
prove = []
for l in range(len(word)):
guess.append("_")
attempts_remaining = 6
print (guess)
print("You have", attempts_remaining, "attempts")
guessed = 0
while guessed < len(word) and attempts_remaining != 0:
if attempts_remaining != 0:
guessed_this_time = 0
prova = input("Write a letter: ")
prove.append(prova)
if prove.count(prova) > 1:
prova = input("You've already tried this letter! Try with another: ")
for l in range(len(word)):
if wordlist[l] == prova:
guess[l] = wordlist [l]
guessed += 1
guessed_this_time += 1
else:
pass
if guessed_this_time == 0:
attempts_remaining -= 1
print(attempts_remaining, "attempts remaining")
elif guessed == len(word):
print("You guessed it!")
print(guess)
if attempts_remaining == 0:
print("You lost, the word was", word)
错误是:
Traceback (most recent call last):
File "/Users/user/Documents/Python/Impiccato/impiccato.py", line 5, in <module>
text = file.read().lower()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position 2170: ordinal not in range(128)
编辑:我“解决”了将所有 txt 内容移动到 .py 并以这种方式调用它:
text = """
here's all the list (the whole thing is 19414Ln LOL)
... """
words = \
re.sub('[^a-z\ \']+', " ", text).split() # Stores the secret words in a list
这样逗号被空格替换。
【问题讨论】:
-
我可以看到一个明显的错误:您不能使用逗号来分割单词表。我想你想要
random.choice(wordlist) -
您遇到的具体错误是什么?
-
文件是oxt不是txt?
-
链接错误,这是正确的下载链接sourceforge.net/project/…@PadraicCunningham
-
@Maltysen wordlist 实际上并不是所有单词的列表(字典),而是一个包含单词字符的列表(在这种明确的情况下,“canestro”是一个意大利语单词)。也许这可以帮助你帮助我:D