繁体   English   中英

如何提取字符串之前的单词?

[英]How can I extract words before some string?

我有几个这样的字符串:

mylist = ['pearsapple','grapevinesapple','sinkandapple'...]

我想在苹果之前解析这些部分,然后追加到新列表中:

new = ['pears','grapevines','sinkand']

除了在每个字符串中找到“苹果”的起点,然后在起点之前追加之外,还有其他方法吗?

通过结合使用切片和字符串的index方法。

>>> [x[:x.index('apple')] for x in mylist]
['pears', 'grapevines', 'sinkand']

您也可以使用正则表达式

>>> import re
>>> [re.match('(.*?)apple', x).group(1) for x in mylist]
['pears', 'grapevines', 'sinkand']

我不明白为什么。

我希望apple这个词将是固定的(固定长度的词),然后我们可以使用:

second_list = [item[:-5] for item in mylist]

如果列表中的某些元素在字符串的末尾不包含'apple' ,则此正则表达式将使字符串保持不变:

>>> import re
>>> mylist = ['pearsapple','grapevinesapple','sinkandapple', 'test', 'grappled']
>>> [re.sub('apple$', '', word) for word in mylist]
['pears', 'grapevines', 'sinkand', 'test', 'grappled']

通过还使用字符串拆分和列表理解

new = [x.split('apple')[0] for x in mylist]
['pears', 'grapevines', 'sinkand']

一种方法是遍历列表中的每个字符串,然后使用split()字符串函数。

for word in mylist:
    word = word.split("apple")[0]

暂无
暂无

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

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