提取以某个字符开头的所有单词

2024-05-14 02:37:24 发布

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

我有一个列表,在其中我把句子存储为字符串。我想做的是只得到以@开头的单词。为了做到这一点,我把句子分成几个单词,现在只挑选以@开头的单词,排除所有其他单词。你知道吗

# to create the empty list:
lst = []

# to iterate through the columns:
for i in range(0,len(df)):
    lst.append(df['col1'][i].split()) 

Tags: columnstheto字符串df列表forcreate
1条回答
网友
1楼 · 发布于 2024-05-14 02:37:24

如果我错了,你只需要一个包含所有以特定字符开头的单词的列表。为此,我将使用列表展平(通过itertools):

import itertools
first = 'f' #look for words starting with f letter
nested_list = [['This is first sentence'],['This is following sentence']]
flat_list = list(itertools.chain.from_iterable(nested_list))
nested_words = [i.split(' ') for i in flat_list]
words = list(itertools.chain.from_iterable(nested_words))
lst = [i for i in words if i[0]==first]
print(lst) #output: ['first', 'following']

相关问题 更多 >