【问题标题】:Python Dictionary Spell Checker, 'TypeError: write() takes no keyword arguments'Python 字典拼写检查器,'TypeError: write() 没有关键字参数'
【发布时间】:2018-04-17 12:43:03
【问题描述】:

我正在使用 python 字典来比较莎士比亚的完整作品和 10,000 个单词的字典,代码应该将在 10,000 个单词的字典中找不到的所有单词输出到一个名为“SpellChecker.txt”的单独文件中。我相信这段代码中的所有内容都运行正常。我只遇到一个与将数据保存到输出文件有关的错误,而且似乎无法修复它。任何帮助表示赞赏。

错误:

Traceback (most recent call last):
  File "/Users/JakeFrench/Desktop/HashTable.py", line 29, in <module>
    f1.write(word+'\n', encoding= 'utf-8')

TypeError: write() 没有关键字参数

import re
import time
start_time = time.time()

f1=open ('SpellChecker.txt', 'w+')

Dictionary = {}
Document = []
with open ('10kWords.txt', encoding= 'utf-8') as f:
        for word in f:
            Dictionary[word.rstrip()] = 1

with open ('ShakespeareFullWorks.txt', encoding= 'utf-8') as f:
    content = f.read().split(" ")
    content = [item.lower() for item in content]
    content = ' '.join(content)
    content = re.findall("\w+", content)
    for line in content:
        Document.append(line)

for line in content:
    for word in line.split():
        if word.lower() not in Dictionary:
            f1.write(word+'\n', encoding= 'utf-8')

f1.close()            

print ("--- %s seconds ---" % (time.time() - start_time))    

【问题讨论】:

  • 删除`.write()中的encoding='utf-8'
  • 嗨 Hamza,我已经尝试过了,当我这样做时出现以下错误: Traceback(最近一次调用最后一次):文件“/Users/JakeFrench/Desktop/HashTable.py”,第 29 行, 在 f1.write(word+'\n') UnicodeEncodeError: 'ascii' codec can't encode character '\xe6' in position 6: ordinal not in range(128)
  • 您应该从 write 函数中删除编码,并将其设置在 open 函数中。
  • 非常感谢!这行得通,现在回头看代码,我意识到这是一个非常愚蠢的错误哈哈,但有时我猜代码就是这样,哈哈
  • 没问题,为了更清楚,我已经在答案表单中添加了评论。

标签: python hashtable


【解决方案1】:

只需将write方法中的encoding属性去掉,插入open函数中即可,如下:

f1=open ('SpellChecker.txt', 'w+', encoding='utf-8')
  ...
f1.write(word+'\n')

【讨论】:

    猜你喜欢
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    相关资源
    最近更新 更多