【发布时间】:2020-05-07 17:33:16
【问题描述】:
我有 python 烧瓶项目(程序),我将用户输入的带有大写字母和标点符号的字符串转换为没有它们的字符串。当我运行程序时,出现以下错误:
ValueError: translation table must be 256 characters long
Traceback (most recent call last) File:
"/home/sd18656/.local/lib/python2.7/site-packages/flask/app.py", line
2463, in __call__ return self.wsgi_app(environ, start_response) File
"/home/sd18656/.local/lib/python2.7/site-packages/flask/app.py", line
2449, in wsgi_app response = self.handle_exception(e) File
"/home/sd18656/.local/lib/python2.7/site-packages/flask/app.py", line
1866, in handle_exception reraise(exc_type, exc_value, tb) File
"/home/sd18656/.local/lib/python2.7/site-packages/flask/app.py", line
2446, in wsgi_app response = self.full_dispatch_request() File
"/home/sd18656/.local/lib/python2.7/site-packages/flask/app.py", line
1951, in full_dispatch_request rv = self.handle_user_exception(e) File
"/home/sd18656/.local/lib/python2.7/site-packages/flask/app.py", line
1820, in handle_user_exception reraise(exc_type, exc_value, tb) File
"/home/sd18656/.local/lib/python2.7/site-packages/flask/app.py", line
1949, in full_dispatch_request rv = self.dispatch_request() File
"/home/sd18656/.local/lib/python2.7/site-packages/flask/app.py", line
1935, in dispatch_request return
self.view_functions[rule.endpoint](**req.view_args) File
"/home/sd18656/FlaskProject/mainapp.py", line 61, in home score,
total_processed_data = get_score(abstract) File
"/home/sd18656/FlaskProject/mainapp.py", line 32, in get_score
abstract = abstract.translate(string.punctuation).lower()
在程序中,abstract 是一个字符串类型。我遇到了这个解决方案:What does "table" in the string.translate function mean? 用于错误,但是,string.maketrans 似乎与lower() 或upper() 不匹配。我该如何解决这个问题?
导致此问题的代码sn-p如下:
r = reader(open('mycsv.csv','r'))
abstract_list = []
score_list = []
institute_list = []
row_count = 0
for row in list(r)[1:]:
institute,score,abstract = row[0], row[1], row[2]
if len(abstract.split()) > 0:
institute_list.append(institute)
score = float(score)
score_list.append(score)
abstract = abstract.translate(string.punctuation).lower()
abstract_list.append(abstract)
row_count = row_count + 1
mycsv.csv 的内容如下:
【问题讨论】:
-
请添加实际产生错误的代码。
-
我们还需要文件 'mycsv.csv'
-
@chepner 我已经添加了代码 sn-p。谢谢。
-
在 translate() 之前使用 string.maketrans() 函数
-
@ManishGupta 实际上我尝试使用 string.maketrans(),但是,即使在 python 文档中也提到:不要使用从小写和大写派生的字符串作为参数;在某些语言环境中,它们的长度不同。对于大小写转换,请始终使用 str.lower() 和 str.upper()。
标签: python string python-2.7