使用i连接列表中单词的两个部分

2024-09-27 18:01:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要连接某些在单词列表中分开显示的单词,例如"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)`

Tags: importfriendcomapple列表ifischeck
2条回答

尽管这个方法不是很健壮(例如,您可能会错过“hamburger”),但主要的错误是您没有在迭代器上循环,而是在列表本身上循环。这是一个正确的版本。你知道吗

请注意,我重命名了变量以提供更具表现力的名称,并用一个简单的word in dic替换了dictionary检查,使用了一个示例词汇表-您导入的模块不是标准库的一部分,这使得您的代码对于我们没有它的人来说很难运行。你知道吗

dic = {'love', 'friend', 'car', 'apple', 
       'computer', 'banana'}

words=['love', 'friend', 'car', 'apple', 'com', 'puter', 'vi']
words_it = iter(words)

valid_words = []

for word in words_it:
    if word in dic:
        valid_words.append(word)
    else:
        try:
            concacenated = word + next(words_it)
            if concacenated in dic:
                valid_words.append(concacenated)
        except StopIteration:
            pass

print (valid_words)
# ['love', 'friend', 'car', 'apple', 'computer']

你需要try ... except部分,以防列表的最后一个单词不在词汇表中,因为在这种情况下next()将引发StopIteration。你知道吗

代码的主要问题是,一方面,在for循环中迭代words,另一方面,通过迭代器myit。这两个迭代是独立的,因此不能在循环中使用next(myit)来获取i之后的单词(同样,如果i是最后一个单词,那么就不会有下一个单词)。另一方面,你的问题可能会变得复杂,因为字典里可能有拆分的单词,其部分太多(例如printable是一个单词,但printable也是一个单词)。你知道吗

假设一个简单的场景,拆分的单词部分永远不会出现在字典中,我认为这个算法对您来说会更好:

import enchant

words = ['love', 'friend', 'car', 'apple', 'com', 'puter', 'vi']
myit = iter(words)
dic = enchant.Dict('en_UK')
lst = []
# The word that you are currently considering
current = ''
for i in words:
    # Add the next word
    current += i
    # If the current word is in the dictionary
    if dic.check(current):
        # Add it to the list
        lst.append(current)
        # Clear the current word
        current = ''
    # If the word is not in the dictionary we keep adding words to current

print(lst)

相关问题 更多 >

    热门问题