簡體   English   中英

unicode方法在Python3中不起作用

[英]unicode method doesn't work in Python3

def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
    csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
    for row in csv_reader:
        yield [unicode(cell, 'utf-8') for cell in row]

filename = '/Users/congminmin/Downloads/kg-temp.csv'
reader = unicode_csv_reader(open(filename))

out_filename = '/Users/congminmin/Downloads/kg-temp.out'
#writer = open(out_filename, "w", "utf-8")
for question, answer in reader:
  print(question+ " " + json.loads(answer)[0]['content'])
  #writer.write(question + " " + answer)

reader.close();

此代碼在Python 2.7中有效。 但是它在Python 3.6中給出了一條錯誤消息:

Unresolved reference 'unicode'

如何使其適應Python 3.6?

只需確保您的數據以str開頭,而不是字節csv.reader ,然后僅使用csv.reader而不進行解碼即可。

data = utf8_data.decode('utf-8')
for row in csv.reader(data, dialect=csv.excel, ...):
    # ...

Python 3已經具有出色的unicode支持。 每次以文本模式打開文件時,都可以使用特定的編碼,也可以將其默認設置為UTF-8。 Python 3中的strunicode之間不再存在區別。后者不存在,並且前者具有完整的unicode支持。 由於根本不需要設置方法,因此極大地簡化了您的工作。 您可以遍歷普通的csv.reader

另外要注意的是,您應該始終在with塊中打開文件,以便在出現任何異常的情況下對它們進行清理。 另外,當塊結束時,您的文件將自動關閉:

with open(filename) as f:  # The default mode is 'rt', with utf-8 encoding
    for question, answer in csv.reader(f):
        # Do your thing here. Both question and answer are normal strings

僅當您確定每一行都包含2個元素時,此方法才能正常工作。 您最好做一些類似的事情

with open(filename) as f:  # The default mode is 'rt', with utf-8 encoding
    for row in csv.reader(f):
        if len(row) != 2:
            continue  # Or handle the anomaly by other means
        question, answer = row
        # Do your thing here as before

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM