【发布时间】:2020-03-11 01:14:30
【问题描述】:
我正在尝试创建一个拼写检查功能,该功能可以读取一个文本文件,其中包含一个包含多个拼写错误的单词的段落。例如:“我最喜欢的科目是:物理、数学、化学树和生物学——我发现课后使用 iPad 做综合笔记很有必要。”我要解决三个问题:
目前,该程序认为 Maths 是一个不正确的词,因为该词后立即出现逗号。我相信为了解决这个问题,最好将文本文件中的字符串拆分成这样:['My', 'favorite', 'subjects', 'are', ':', ' ', '物理','','数学',','...等]。如何在不使用任何导入的 python 函数(例如字符串或 regex (re) 函数)的情况下将字符串拆分为单词和标点符号?
我目前正在通过迭代文本文件中的每个单词来将每个单词与接受的英语单词字典进行比较。有没有更好的方法来预处理列表以快速识别单词是否包含给定元素以提高程序的运行时间?
“eBook”和“iPad”等几个词是下面函数
is_valid_word中使用的规则的例外(即,该词必须以大写字母开头,所有其他字母为小写或单词中的所有字符都必须大写)。有什么方法可以检查字符串是否为有效单词?
任何帮助将不胜感激!
def get_words():
with open( "english.txt" ) as a:
words = a.readlines()
words = [word.strip() for word in words]
return words
isWord = get_words()
def is_valid_word(st):
if isinstance(st, str):
st_lower = st.lower()
if st_lower in isWord:
if (st[0:len(st)].isupper() or st[0:len(st)].islower()) or (st[0].isupper() and st[1:len(st)].islower()) or st[0:len(st)].isupper():
return (True)
else:
return(False)
else:
return (False)
else:
return (False)
def spell_check_file( file ):
incorrectWords = [] # Will contain all incorrectly spelled words.
num = 0 # Used for line counter.
with open(file, 'r') as f:
for line_no, line in enumerate(f):
for word in line.split():
if is_valid_word(word) == False:
incorrectWords.append(line_no)
incorrectWords.append(word)
for f in incorrectWords:
return incorrectWords
print (incorrectWords)
spell_check_file("passage.txt")
【问题讨论】:
-
为什么不想使用 Python 内置函数?
-
.isupper()和.islower()无论如何都是内置函数。 -
当我说内置函数时,我指的是任何需要导入的函数(例如字符串),因为我正在使用的练习簿指示我们只使用 split()、strip()、replace () 等。抱歉,我认为我最初的问题并不明确 - 我会相应地对其进行修改。
-
Third answer here 提供了一种仅使用拆分和替换(即不导入)来分离单词的方法。
标签: python string spell-checking