【问题标题】:using unicode in python for Farsi在 python 中为波斯语使用 unicode
【发布时间】:2015-07-18 06:06:47
【问题描述】:

我正在编写一个脚本来读取语料库文件并查找后缀。由于语料库中有波斯语单词,它是 UTF-8 编码的,但是当我使用波斯语后缀进行搜索时,我没有得到任何结果,而英文结果却很好。

from __future__ import unicode_literals
import nltk
import sys


for line in open("corpus.txt"):
for word in line.split():
     if word.endswith('ب'):
        print (word)

【问题讨论】:

  • 你说的我没有结果是什么意思?
  • 你的 python 版本是什么? (看来你在 python 3 中)但我需要确定!
  • 我使用的是 Python 3.4,实际上我在 shell 中没有得到任何结果,就好像语料库中没有单词一样,@Kasra
  • 在 python 3 中,您也不需要 from __future__ import unicode_literals ,您的代码将运行良好!但是您的文件中有任何以ب 结尾的单词吗?
  • 我已经导入了 'from future import unicode_literals ',但它不起作用,而且我确实有以“b”结尾的单词。无论如何打开文件为 UTF-8 'with open("corpus.txt", encoding="utf-8") as fp:' 对我有用。

标签: python unicode utf-8


【解决方案1】:

在 Python 3 中,您只需将 encoding=utf-8 传递给 open

with open("corpus.txt", encoding="utf-8") as fp:
    for line in fp:
        for word in line.split():
            process(word)

在 Python 2 中,您需要执行以下操作:

import codecs
with codecs.open("corpus.txt", encoding="utf-8") as fp:
    for line in fp:
        for word in line.split():
            process(word)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多