Skip to main content
 首页 » 编程设计

python之初学者 python 翻译器 : I am unable to convert a list from shelve module into a string

2025年05月04日14dudu

我正在尝试制作一个简单的翻译器,它可以从搁置模块中的字典中输入英文单词,程序会逐字翻译输入的内容,然后将结果放入 .txt 文件中。到目前为止,这几乎就是我所拥有的。

import shelve 
 
s = shelve.open("THAI.dat") 
entry = input("English word") 
define = input("Thai word") 
s[entry]=define 
 
text_file = open("THAI.txt", "w+") 
trys = input("Input english word") 
 
if trys in s: 
    print(s[trys]) 
    part = s[trys] 
    text_file.write(part) 

这是出现错误的地方。我认为问题在于该部分是一个列表,应该是一个能够写入 .txt 文件的字符串。我应该怎么办。我只是一个初学者,所以我可能缺少一些基本的东西。这是错误。

Traceback (most recent call last): 
  File "C:\Users\Austen\Desktop\phython fun\thai translator.py", line 29, in <module> 
    text_file.write(part) 
TypeError: must be str, not list 
>>>  

最后我希望能够做到这一点

text_file.readlines()  

然后甚至可以进入文本文件并查看翻译。

请您参考如下方法:

根据您的评论,除了没有 s[entry]=[define] 之外,我认为您需要使用正确的编解码器来读写泰文文件。

假设文件 thai.dat 是用 UTF-8 编写的(假设),您现在需要使用相同的编解码器比较字符串,并使用相同的编解码器写入数据文件。

首先,从您的命令 shell 中尝试以下行:

python -c 'import sys; print sys.getdefaultencoding()' 

如果它打印出 ascii,那么您可能需要将默认编码设置为 UTF-8,否则字符串比较将无法正常工作。

此外,您需要像这样以 UTF-8 模式打开输出文件:

>>>import codecs 
>>>f = codecs.open("THAI.txt", "w+", "utf-8") 

然后像往常一样写入这个文件。