gpt4 book ai didi

python - 我正在编写一个拼写检查程序,如何替换字符串中的 ch ?

转载 作者:行者123 更新时间:2023-11-30 23:58:43 24 4
gpt4 key购买 nike

我做错了什么/我能做什么?

import sys
import string

def remove(file):
punctuation = string.punctuation
for ch in file:
if len(ch) > 1:
print('error - ch is larger than 1 --| {0} |--'.format(ch))
if ch in punctuation:
ch = ' '
return ch
else:
return ch

ref = (open("ref.txt","r"))
test_file = (open("test.txt", "r"))

dictionary = ref.read().split()
file = test_file.read().lower()
file = remove(file)
print(file)

这是 Python 3.1.2 中的

最佳答案

在此代码中...:

for ch in file:
if len(ch) > 1:

这个名字奇怪的文件(除了打破了不用你自己的标识符隐藏内置名称的最佳实践之外)不是一个文件,它是一个字符串——在Python 3中这意味着unicode,但是这与循环返回单个字符(Python 3 中的 unicode 字符,而不是字节)这一事实没有区别,因此 len(ch) == 1 绝对由 Python 语言的规则保证。不确定你想通过该测试完成什么(排除一些 unicode 字符子集?),但是,无论你要实现什么,我向你保证你不是实现它并应该重新编码该部分。

除此之外,您将立即返回并因此退出该函数,从而退出该函数并仅返回一个字符(文件中的第一个字符,如果第一个字符是标点符号,则返回一个空格字符)。

我在另一个答案中看到的使用 translate 方法的建议是正确的,但该答案使用了错误版本的 translate (一个适用于字节字符串,不是 Python 3 所需的 unicode 字符串)。正确的 unicode 版本更简单,并将函数的整个主体转换为两个语句:

trans = dict.fromkeys(map(ord, string.punctuation), ' ')
return file.translate(trans)

关于python - 我正在编写一个拼写检查程序,如何替换字符串中的 ch ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2893875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com