简体   繁体   English

列表理解(从句子中提取单词)

[英]List comprehension (extracting words from a sentence)

I am trying to use list comprehension in order to extract only words which have characters which is greater then 3. I already made this line of code which count that words.我正在尝试使用列表理解来仅提取字符大于 3 的单词。我已经制作了这行代码来计算这些单词。

ListWord = [len(x.strip(',')) for x in 'Michael Jordan is the best basketball player of all time'.split() if len(x.strip(','))>3]

    ListWord
    Out[73]: [7, 6, 4, 10, 6, 4]

But now I need to see that words not only to count е.g["Michael","Jordan","best","basketball","player","time"].但现在我需要看到这些词不仅要计算е.g["Michael","Jordan","best","basketball","player","time"]. So can anybody help me how to solve this problem?那么有人可以帮我解决这个问题吗?

Replace len(x.strip(',')) with x.strip(',')将 len(x.strip(',')) 替换为 x.strip(',')

ListWord = [x.strip(',') for x in 'Michael Jordan is the best basketball player of all time'.split() if len(x.strip(','))>3]

print(ListWord)

Let's take a look at your query.让我们看一下您的查询。

[len(x.strip(',')) for x in 'Michael Jordan is the best basketball player of all time'.split() if len(x.strip(','))>3]

If we break this into components, it will be如果我们将其分解为组件,它将是

[TO_RETURN for CURRENT_ITEM in LIST if CONDITION]

So, if you would like to return something different, replace TO_RETURN .因此,如果您想返回不同的东西,请替换TO_RETURN In this case, x.strip(',') instead of len(x.strip(',')) .在这种情况下, x.strip(',')而不是len(x.strip(','))

Why are you using strip?你为什么用条带? Simpler to just .split() (that returns a list of each item) of the string, and then check the length of each item in that list:更简单的只是字符串的.split() (返回每个项目的列表),然后检查该列表中每个项目的长度:

list_word = [x for x in 'Michael Jordan is the best basketball player of all time'.split() if len(x)>3]

Output: Output:

print(list_word)
['Michael', 'Jordan', 'best', 'basketball', 'player', 'time']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM