【问题标题】:how to print the next word of a sprecific string in a line using python?如何使用python打印一行中特定字符串的下一个单词?
【发布时间】:2020-11-06 14:03:23
【问题描述】:

我正在尝试打印“”中的文本

s="I love playing "badminton", it is a great sport."
s1 = re.search('playing (\w+)', s).groups()[0]
print (s1)

如果输入是“我喜欢打羽毛球,这是一项很棒的运动”,上面的代码就可以完美运行。以这种格式。我正在尝试打印“”中的任何文本。我相信这很简单,因为学习 python 的初始阶段不知道我到底要去哪里。任何帮助,将不胜感激。谢谢

【问题讨论】:

  • 用双引号将单词 chars 括起来 \bplaying "(\w+)" 或使用否定字符类 \bplaying "([^"]+)" 值在第 1 组中。
  • @Thefourthbird 如果我想在输出中包含“playing”这个词怎么办。这意味着它应该喜欢“打羽毛球”
  • 那么你可以使用2个capturin组\b(playing )"(\w+)"regex101.com/r/m3dHE3/1
  • 成功了吗?
  • @Thefourthbird 它也在尝试其他情况,例如,如果我们以上述语句为例,我们必须在播放后打印文本无论它是否在“”中。任何想法。谢谢

标签: python-3.x regex


【解决方案1】:

尝试转义(\)字符串s 中的引号,这样python 会将它们视为字符串的一部分。然后可以选择在您的正则表达式中匹配它们,您可以使用?

import re

s = "I love playing \"badminton\", it is a great sport."
s1 = re.search('playing "?(\w+)"?', s).groups()[0]
print(s1)

# prints
badminton

【讨论】:

    【解决方案2】:

    如果要打印playing badminton,可以使用2个捕获组,并将双引号放在组外。

    您也可以使用.group(1) 来代替.groups()[0] 中的索引

    \b(\w+ )"(\w+)"
    

    Regex demo

    示例代码

    import re
    
    s = """I love playing "badminton", it is a great sport."""
    s1 = re.search(r'\b(\w+ )"(\w+)"', s)
    if s1:
        print (s1.group(1) + s1.group(2))
    

    输出

    playing badminton
    

    或者,如果双引号可以是其他非单词字符或不存在,您可能会匹配所有非单词字符直到下一个单词。

    \b(playing )\W*(\w+)
    

    Regex demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      • 2018-11-23
      • 2022-11-13
      • 1970-01-01
      相关资源
      最近更新 更多