“无法在'013U'中解决'013U'字符编码错误'

2024-09-29 02:19:25 发布

您现在位置:Python中文网/ 问答频道 /正文

向文件写入字符串时出错。在

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 16: ordinal not in range(128)

问题是我已经把绳子清理干净了。但不知道为什么这样不行

这是我清理字符串的代码

^{pr2}$

你知道我在清理绳子的时候遗漏了什么吗?在

我知道这个问题被问了很多次。但我的问题是这个问题最常见的解决方法是

text.encode('utf-8')

这对我没用。在

我也试过了

text.encode('utf-8', 'ignore')

没用


Tags: 文件字符串textinasciipositioncanutf
1条回答
网友
1楼 · 发布于 2024-09-29 02:19:25

不知道它给你带来了什么错误。我刚刚在windows上的python 2.7.10中测试了这一点:

# -*- coding: utf8 -*-
import string

replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))

def clean_text(text):
    try:
        text = text.decode('utf-8', 'ignore')
    except:
        text = text.encode('utf-8', 'ignore')
        text = text.decode('utf-8', 'ignore')
    text = text.encode('ascii', 'ignore').lower().translate(replace_punctuation)
    text = " ".join(text.split())
    return text

text = "some text öäööäwith special characters"
text = clean_text(text)
print text
with open('test.txt','w') as outfile:
    outfile.write(text)

>>>
some text with special characters

该文件也包含相同的文本。在

这可能是另一种选择:

^{pr2}$

你过滤掉了不在ascii中的字符,所以你不必担心unicode。在

相关问题 更多 >