【问题标题】:Concatenate two lines if they are not empty如果两行不为空,则连接它们
【发布时间】:2016-06-24 13:17:47
【问题描述】:

我想将 2 行文本合并为一行,但前提是它们都不是空行。例如:

1:1 Bob drives his car.
1:2 Bob and his wife are going on a trip. 
They will have an awesome time on the beach.

我想将它们放入这样的字典中:

dict[1:1] gives me "Bob drives his car."
and dict[1:2] must give me "Bob and his wife are going on a trip.They will have an awesome time on the beach."

我知道如何解决第一个问题 (dict[1:1]),但我不知道如何将这两个句子放在一起。

或者是否有一个选项,如果一个句子后面跟着另一个句子,你可以把它们放在一行?这只是现实中的一个例子,文件包含100000行。

【问题讨论】:

  • 文件本身中有1:1的注解吗?
  • 是的,他们是。它从 1:1 到 1:25,然后从 2:1 到 2:25。以此类推。

标签: python string python-3.x dictionary


【解决方案1】:

您可以这样做 - 从文件中一次读取一行,如果有空行则触发新部分的开始。

start_new_section = True
key = None
output = {}
with open('file.txt', 'r') as f:
    for line in f:
        if line == '':
            start_new_section = True
        elif start_new_section:
            words = line.split(' ')
            key = words[0]
            output[key] = ' '.join(words[1:])
            start_new_section = False
        else:
            output[key] += line

print(output)

或者相同想法的更简洁的版本:

key = None
output = {}
with open('file.txt', 'r') as f:
    for line in f:
        if not line:
            key = None
        elif key:
            output[key] += line
        else:
            key, _, output[key] = line.partition(' ')

【讨论】:

    【解决方案2】:

    解决此问题的一种可能方法是浏览文件一次,并列出以数值开头的索引。然后您可以使用索引来创建您的字典,因为您知道索引中的每 2 个数字都包含一个应该插入到字典中的项目。

    【讨论】:

      【解决方案3】:

      假设文件足够小,您可以将整个内容读入内存,您可以使用正则表达式来解析块。这是example in action

      import re
      
      with open('file.txt', 'r') as f:
          txt = f.read()
      
      matches = re.findall(r'^(\d+:\d+) (.+?)$(?=(?:\s^\d+:\d+)|\z)', txt, flags=re.M | re.S)
      d = {m[0]: m[1].replace(r'\n', '') for m in matches}
      

      【讨论】:

      • 是的,可以完成这项工作。但实际上这个问题比我的例子更复杂。但是我可以运行这样的代码来重构文件吗?所以文件变成:> 1:1 Bob drives his car. > > 1:2 Bob and his wife are going on a trip. They will have an awesome time on the beach. >
      • 您的文件如何更复杂?您的文件实际上是否在每一行都包含 > 字符?
      • No the ">" 代表一行的开始。但是是否可以更改文件。所以两行接二连三,中间没有换行符。会改成一行吗?
      • 是的,它假定所有文本块都由 2 个换行符分隔。
      • 它们实际上只用 1 个换行符分隔。像这样 1:1 一些文字 [NEWLINE] 1:2 一些文字 文字也是 1:2 的一部分
      猜你喜欢
      • 2016-06-25
      • 2012-01-27
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多