【问题标题】:Writing a dictionary to csv works with file from UbuntuVM but not from Windows将字典写入 csv 适用于来自 UbuntuVM 的文件,但不适用于来自 Windows 的文件
【发布时间】:2020-07-09 20:06:15
【问题描述】:
from sys import argv
from PyDictionary import PyDictionary
import csv

name, filename = argv

d = PyDictionary()

csv_columns = ['Word', 'Noun', 'Verb', 'Adjective', 'Adverb']
csv_file = 'trans_test.csv'
try:
    with open(csv_file, 'w+') as f:
        with open(filename, 'r') as g:
            w = csv.DictWriter(f, fieldnames = csv_columns)
            w.writeheader()
            for i in g:
                word = (i.split(' ')[0])
                dict1 = d.meaning(word)
                dict1['Word'] = word
                w.writerow(dict1)
except IOError:
    print('I/O error')

我遇到了错误:

Erorr: The Following Error occured: list index out of range
Traceback (most recent call last):
File "my_trans.py", line 19 in module<>
dict1['Word'] = word
TypeError: 'NoneType' object does not support item assignment

我正在尝试从 txt 文件中的每一行中提取第一个单词,获取该单词的定义,将其放入字典中,将带有键 'Word' 的单词添加到该字典并写入这个到 csv 文件。

我尝试和检查的内容

-dict1 是 NoneType,我不知道为什么 - 但是当我将 dict1 = d.meaning(word) 放在外面尝试时,dict1 是字典

-我在 UbuntuVM 上工作,当我在 VM 上创建带有单词的 file.txt 时,脚本可以工作,但是当我在 Windows 上使用记事本创建的文件时出现此错误

-如果我在 UbuntuVM 上写下文件的内容,脚本可以工作,但如果我将从 Windows 带来的文件内容复制到 Ubuntu 中的文件,它也不起作用

-Windows 记事本中的文件以 utf-8 格式保存

file.txt 看起来像这样:

renowned - (known or talked about by many people; famous)
prevalent - (widespread in a particular area at a particular time)
lesion - 
aneurysm - (an excessive localized enlargement of an artery caused by a weakening of the artery wall)
ischemic - 
juvenile - 
ashen - (of the pale gray color of ash)
inflammation - 
conned - 
intermittent - (occurring at irregular intervals; not continuous or steady)
mild - 

【问题讨论】:

    标签: python csv dictionary nonetype


    【解决方案1】:

    PyDictionary.meaning 抓取http://wordnetweb.princeton.edu 以获取定义。看起来正在发生的事情是它未能检索到预期的内容,这会导致PyDictionary 出现错误:

    错误:发生以下错误:列表索引超出范围

    在这种情况下,PyDictionary.meaning 返回None,导致您看到的 TypeError。

    这可能是暂时的问题,也可能是您的 Windows 环境中的某些问题导致了该错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 2011-03-09
      • 2021-08-08
      • 2021-01-03
      • 2020-07-04
      相关资源
      最近更新 更多