我需要连接某些在单词列表中分开显示的单词,例如"computer"
(下面)。由于换行符,这些单词在列表中分开显示,我想解决这个问题。你知道吗
lst=['love','friend', 'apple', 'com', 'puter']
预期结果是:
lst=['love','friend', 'apple', 'computer']
我的代码不起作用。有人能帮我吗?你知道吗
我尝试的代码是:
from collections import defaultdict
import enchant
import string
words=['love', 'friend', 'car', 'apple',
'com', 'puter', 'vi']
myit = iter(words)
dic=enchant.Dict('en_UK')
lst=[]
errors=[]
for i in words:
if dic.check(i) is True:
lst.append(i)
if dic.check(i) is False:
a= i + next(myit)
if dic.check(a) is True:
lst.append(a)
else:
continue
print (lst)`
尽管这个方法不是很健壮(例如,您可能会错过“hamburger”),但主要的错误是您没有在迭代器上循环,而是在列表本身上循环。这是一个正确的版本。你知道吗
请注意,我重命名了变量以提供更具表现力的名称,并用一个简单的
word in dic
替换了dictionary检查,使用了一个示例词汇表-您导入的模块不是标准库的一部分,这使得您的代码对于我们没有它的人来说很难运行。你知道吗你需要
try ... except
部分,以防列表的最后一个单词不在词汇表中,因为在这种情况下next()
将引发StopIteration
。你知道吗代码的主要问题是,一方面,在
for
循环中迭代words
,另一方面,通过迭代器myit
。这两个迭代是独立的,因此不能在循环中使用next(myit)
来获取i
之后的单词(同样,如果i
是最后一个单词,那么就不会有下一个单词)。另一方面,你的问题可能会变得复杂,因为字典里可能有拆分的单词,其部分太多(例如printable
是一个单词,但print
和able
也是一个单词)。你知道吗假设一个简单的场景,拆分的单词部分永远不会出现在字典中,我认为这个算法对您来说会更好:
相关问题 更多 >
编程相关推荐