【问题标题】:How to print specific characters in a line using python?如何使用python在一行中打印特定字符?
【发布时间】:2020-07-15 21:17:25
【问题描述】:

我正在尝试编写一个脚本来在特定字符串之后打印特定单词。

这是输入文件

Theyare "playing in the ground", with friends
Theyare "going to Paris", with family
Theyare "motivating to learn new things", by themselves

在输出中,我尝试选择“are”作为关键字,在“are”之后,我想要“”中的文本,并且我想将空格前的文本添加到“”。

输出应该是

They playing in the ground
They going to Paris
They motivating to learn new things

我可以使用以下代码打印该行的其余部分,但不能打印某些单词。到目前为止我有

with open ('input.txt', 'r') as f:
    for lines in f:
        a = re.search(r'\bare', f):
            if a:
                print (lines)
            

任何帮助将不胜感激

【问题讨论】:

    标签: python-3.x regex


    【解决方案1】:

    使用正则表达式提取你想要的行的部分。

    with open ('input.txt', 'r') as f:
        for lines in f:
            m = re.match(r'(.*?) are "(.*?)"')
            if m:
                print m.group(1) + " " + m.group(2)
    

    m 中的组返回与() 之间的模式匹配的行部分。

    【讨论】:

      【解决方案2】:

      如果您的行总是看起来像您提供的示例,您可以使用字符串操作:

          s = 'They are "playing in the ground", with friends'
          are_split = s.split('are')
          # are_split = ['They ', ' "playing in the ground", with friends']
          quote_split = are_split[1].split('"')
          # quote_split = [' ', 'playing in the ground', ', with friends']
          print(are_split[0] + quote_split[1])
          # 'They playing in the ground'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-23
        • 2018-03-16
        相关资源
        最近更新 更多