簡體   English   中英

蟒蛇。 分割一部分以特定字符開頭和以字符結尾的字符串

[英]Python. slice a part of the string that begins with a specific character and end with a character

我想在選擇的角色之后提取信息,然后在選擇的角色之前停止; 例如,從*提取並以空格結尾,然后將識別出的單詞放入新列表中。

>>> extract_star('*we are *engineers *happy very *much')
['we', 'engineers', 'happy', 'much']

我試着使用splitfind函數,或者用startswithendswith函數檢查布爾類型……但是它並沒有真正起作用。

您可以為此使用正則表達式

import re

def extract_star(s):
    return re.findall(r'\*(.+?)\b', s)

extract_star('*we are *engineers *happy very *much')
# ['we', 'engineers', 'happy', 'much']

這會收集所有.+? 組(非貪婪的任何一個或多個),后跟一個'*'和一個單詞邊界'\\b' (如果有空格,您會錯過最后一個匹配項)。

看來您已接近所知道的方法:

  • 在空格處分割字符串
  • 查找以*開頭的元素
  • 保留那些元素的其余部分

    extract_star(s):單詞= s.split()star_words = [如果word.startswith('*')],則以單詞為單位的單詞結果= [star_words中的單詞為word [1:]返回結果

...或者用一種表達方式...

return [word[1:] for word in s.split() if word.startswith('*')]

您可以用'*'分割,忽略空字符串,用空格分割,然后提取第0個值:

def extract_star(x):
    return [i.split(maxsplit=1)[0] for i in x.split('*') if i]

res = extract_star('*we are *engineers *happy very *much')

['we', 'engineers', 'happy', 'much']

或功能上:

from operator import itemgetter

def extract_star(x):
    return list(map(itemgetter(0), map(str.split, filter(None, x.split('*')))))

其余部分提供了很多選擇,以字符開頭的方式進行顯示。

如果它不是以特殊字符開頭 (即使是),則可以嘗試執行以下操作。

def extract_star(sentence, sc = '*'):
    mywords = sentence.split()
    res = [word[:word.find(sc)] + word[word.find(sc) + 1:] for word in mywords if sc in word]
    return res

result = extract_star('*we are *engineers *happy very *much')
result = extract_star('*we are *engineers *happy very m*uch')

['we', 'engineers', 'happy', 'much']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM