簡體   English   中英

隔離字符串的第一個單詞

[英]Isolating the first word of a string

這是我到目前為止編寫的代碼:

def first_word(text: str) -> str:
    while text.find(' ') == 0:
       text = text[1:]
    while text.find('.') == 0:
        text = text[1:]
    while text.find(' ') == 0:
        text = text[1:]
    while text.find('.') == 0:
        text = text[1:]
    if text.find('.') != -1:
        text = text.split('.')
    elif text.find(',') != -1:
        text = text.split(',')
    elif text.find(' ') != -1:
        text = text.split(' ')
    text = text[0]
    return text

它應該隔離字符串中的第一個單詞,它應該刪除任何“。”,“”,“,”並只保留單詞本身。

使用resplit()

import re
ss = 'ba&*(*seball is fun'
print(''.join(re.findall(r'(\w+)', ss.split()[0])))

輸出:

baseball
sentence="bl.a, bla bla"
first_word=first_word.replace(".","").replace(",","")
first_word=sentence.split(" ")[0]
print(first_word)

或者您可以嘗試列表理解:

sentence="bl.a, bla bla"
first_word=''.join([e for e in first_word if e not in ".,"]) #or any other punctuation
first_word=sentence.split(" ")[0]
print(first_word)

暫無
暫無

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

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