【问题标题】:Find first word in string Python在字符串 Python 中查找第一个单词
【发布时间】:2018-01-04 10:56:54
【问题描述】:

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

("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 text.split()[0]
return re.split(r'\w*, text)[0]

在某些字符串上都出错了,谁能帮帮我???

【问题讨论】:

  • re.search(r'\w+', text).group()?
  • @cᴏʟᴅsᴘᴇᴇᴅ 将返回don 而不是don't ;) 试试re.search('[\w\']+', s).group()
  • @DeepSpace 这个问题的烦人之处在于对单词的一部分和非单词的任意限制。
  • 可以使用[\w']+ 查找所有单词成分和撇号,但这会很快导致"'No!' he shouted" 之类的输入出现问题('No 可能不需要)。

标签: python regex string-function


【解决方案1】:

试试下面的代码。我用你的所有输入进行了测试,效果很好。

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 太棒了!感谢您的输入!
    【解决方案3】:

    试试这个:

    >>> 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
    

    【讨论】:

      【解决方案4】:

      非正则表达式解决方案:去除前导标点/空白字符,拆分字符串以获得第一个单词,然后删除尾随标点/空白:

      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#
      

      【讨论】:

        【解决方案5】:

        你可以试试这样的:

        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
        

        【讨论】:

          【解决方案6】:

          我通过使用第一次出现的空格来阻止“获取”第一个单词来做到这一点。像这样的:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-01-22
            • 2013-04-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多