【问题标题】:Python - Removing text after first instance of specific string and doing it again with a different stringPython - 在特定字符串的第一个实例之后删除文本并使用不同的字符串再次执行
【发布时间】:2021-09-22 04:07:09
【问题描述】:

我有一个将某些语音导出为文本的文本文件。它旨在通过在行首放置 1 或 2 来跟踪谁在说话。但是,它会根据服务信心创建一条新线路。

我一直在尝试使用 Python 删除新行并加入人员 1 和 2 发言的实例。我对 Python 还很陌生,我目前的最佳猜测是一系列 if 和 else 语句,但没有运气。

文本当前显示为...

1   Hello and welcome

1   to this interview

1   Let's start by asking a few

1   questions

2   What questions

2   Do you have?

我正在努力让它像......

1   Hello and welcome to this interview Let's start by asking a few questions

2   What questions Do you have?

我当前的代码是这样的......因为我尝试过的所有其他方法似乎都不起作用。

 input = open("/mnt/d/Visual Studio
> Code/PythonStuff/TextReplace/SpeakerText.txt", "rt")
> 
> output = open("replacted_text.txt", "wt")
> 
> 
> for line in input:
> 
>     output.write(line.replace("1  ", "Speaker 1: ").replace("2    ", "Speaker 2: "))
> 
> 
> input.close() output.close()

我没有运气找到类似的问题,所以任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: python string loops if-statement replace


    【解决方案1】:

    我们可以在这里使用正则表达式迭代方法。解析输入文本,然后构建带编号的问题,然后将其存储在字典中。

    inp = """1 Hello and welcome
    1 to this interview
    1 Let's start by asking a few
    1 questions
    2 What questions
    2 Do you have?"""
    
    num = "1"
    questions = {}
    
    for m in re.finditer(r'^(\d+) (.*)$', inp, flags=re.MULTILINE):
        num_curr = m.group(1)
        if num_curr not in questions:
            questions[num_curr] = m.group(2)
            num = num_curr
        else:
            questions[num_curr] = questions[num_curr] + ' ' + m.group(2)
    
    print(questions)
    

    打印出来:

    {'1': "Hello and welcome to this interview Let's start by asking a few questions",
     '2': 'What questions Do you have?'}
    

    【讨论】:

      【解决方案2】:

      一种使用collections.defaultdict的方式:

      from collections import defaultdict
      
      d = defaultdict(list)
      
      for line in input:
          num, txt = line.split(maxsplit=1)
          d[num].append(txt)
      for k, v in d.items():
          print(k, " ".join(v))
      

      输出:

      1 Hello and welcome to this interview Let's start by asking a few questions
      2 What questions Do you have?
      

      【讨论】:

        猜你喜欢
        • 2018-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-17
        • 1970-01-01
        • 2020-05-16
        相关资源
        最近更新 更多