查找字符串中的第一个单词 Python

Find first word in string Python

我必须编写一个函数,它应该 return 以下字符串中的第一个单词:

("Hello world") -> return "Hello"
(" a word ") -> return "a"
("don't touch it") -> return "don't"
("greetings, friends") -> return "greetings"
("... and so on ...") -> return "and"
("hi") -> return "hi"

所有都必须 return 第一个单词,正如您所看到的,有些以空格开头,有撇号或以逗号结尾。

我使用了以下选项:

return text.split()[0]
return re.split(r'\w*, text)[0]

部分字符串都出错了,谁能帮帮我???

试试下面的代码。我测试了你所有的输入,它工作正常。

import re
text=["Hello world"," a word ","don't touch it","greetings, friends","... and so on ...","hi"]
for i in text:
    rgx = re.compile("(\w[\w']*\w|\w)")
    out=rgx.findall(i)
    print out[0]

输出:

Hello
a
don't
greetings
and
hi

很难区分应该是单词一部分的撇号和语法标点符号的单引号。但是由于您的输入示例不显示单引号,我可以这样做:

re.match(r'\W*(\w[^,. !?"]*)', text).groups()[0]

对于您的所有示例,这都有效。不过,它不适用于 "'tis all in vain!" 等非典型内容。它假定单词以逗号、点、空格、刘海、问号和双引号结尾。可以根据需要扩展此列表(在括号中)。

非正则表达式解决方案:剥离前导 punctation/whitespace 字符,拆分字符串以获得第一个单词,然后删除尾随 punctuation/whitespace:

from string import punctuation, whitespace

def first_word(s):
    to_strip = punctuation + whitespace
    return s.lstrip(to_strip).split(' ', 1)[0].rstrip(to_strip)

tests = [
"Hello world",
"a word",
"don't touch it",
"greetings, friends",
"... and so on ...",
"hi"]

for test in tests:
    print('#{}#'.format(first_word(test)))

输出:

#Hello#
#a#
#don't#
#greetings#
#and#
#hi#

试试这个:

>>> def pm(s):
...     p = r"[a-zA-Z][\w']*"
...     m = re.search(p,s)
...     print m.group(0)
... 

测试结果:

>>> pm("don't touch it")
don't
>>> pm("Hello w")
Hello
>>> pm("greatings, friends")
greatings
>>> pm("... and so on...")
and
>>> pm("hi")
hi

您可以尝试这样的操作:

import re
pattern=r"[a-zA-Z']+"
def first_word(words_tuple):
    match=re.findall(pattern,words_tuple)
    for i in match:
        if i[0].isalnum():
            return i



print(first_word(("don't touch it")))

输出:

don't

我通过使用第一次出现的白色 space 来阻止第一个单词的“获取”来完成此操作。像这样:

stringVariable = whatever sentence
firstWord = ""
stringVariableLength = len(stringVariable)
for i in range(0, stringVariableLength):
    if stringVariable[i] != " ":
        firstWord = firstWord + stringVariable[i]
    else:
        break

此代码将解析要获取第一个单词的字符串变量,并将其添加到名为 firstWord 的新变量中,直到它第一次出现白色 space。我不太确定你会如何将它放入一个函数中,因为我对这整件事还很陌生,但我相信它可以完成!