隔离字符串的第一个单词

问题描述 投票:-3回答:2

这是我到目前为止编写的代码:

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

它应该隔离字符串中的第一个单词,它应该删除任何“。”,“”,“,”并且只保留单词本身。

python
2个回答
1
投票
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)

2
投票

使用resplit()

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

输出:

baseball
© www.soinside.com 2019 - 2024. All rights reserved.