隔离字符串的第一个单词

时间:2018-03-05 22:53:39

标签: python

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

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

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

2 个答案:

答案 0 :(得分:2)

使用resplit()

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

输出:

baseball

答案 1 :(得分: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)