【问题标题】:Put u in front of text python把你放在文本python前面
【发布时间】:2020-06-22 21:47:08
【问题描述】:

我尝试用 ascii 字符替换非 ascii 字符。

效果很好:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unidecode import unidecode

in_text = u"protégé"

out = unidecode(in_text)

print out

结果:protA(c)gA(c)

在这种情况下,我必须手动复制文本。

问题出在文本前面的'u'。

我想自动阅读。像这样的:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unidecode import unidecode

with open("C:\Users\B\Desktop\\0.txt", "r") as f:
    in_text = f.read()
    
char_text = u(in_text)

out = unidecode(char_text)

蟒蛇2.7 https://pypi.org/project/Unidecode/

【问题讨论】:

    标签: python non-ascii-characters


    【解决方案1】:

    仅适用于 python2:

    from unidecode import unidecode
    import io
    
    with io.open("C:\Users\B\Desktop\\0.txt", "r", encoding="utf-8") as file:
        for line in file:
            char_text = u"{}".format(line)
            out = unidecode(char_text)
        print(out)
    

    【讨论】:

    • 显示错误:回溯(最近一次调用最后一次):文件“C:/Users/Big Daddy/PycharmProjects/untitled/remove non ascii.py”,第 7 行,在 char_text = u "{}".format(line) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)
    • 我添加了 encoding = "utf-8" 尝试在我对其进行编辑后再次使用上面的代码。
    • 不同的错误:第 3 行,在 中使用 open("C:\Users\Big Daddy\Desktop\\0.txt", "r", encoding="utf-8") as file: TypeError: 'encoding' is an invalid keyword argument for this function
    • 你用的是什么版本的python?
    • 我使用的是 python 2.7
    猜你喜欢
    • 2019-06-08
    • 2020-11-15
    • 2020-07-07
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 2012-08-14
    • 1970-01-01
    相关资源
    最近更新 更多