python - 根据第一列中的字母数将行与上一行连接起来

标签 python regex python-3.x csv concatenation

刚接触编码并试图弄清楚如何修复损坏的 csv 文件以使其能够正常使用。

因此该文件已从案例管理系统导出,并包含用户名、案例、花费的时间、备注和日期等字段。

问题是偶尔的注释中有换行符,并且在导出 csv 时,工具不包含引号以将其定义为字段中的字符串。

看下面的例子:

user;case;hours;note;date;
tnn;123;4;solved problem;2017-11-27;
tnn;124;2;random comment;2017-11-27;
tnn;125;3;I am writing a comment
that contains new lines
without quotation marks;2017-11-28;
HJL;129;8;trying to concatenate lines to re form the broken csv;2017-11-29;

我想连接第 3、4 和 5 行以显示以下内容: tnn;125;3;我正在写一条评论,其中包含没有引号的新行;2017-11-28;

由于每一行都以用户名开头(总是 3 个字母),我想我可以遍历这些行以找到哪些行不以用户名开头并将其与上一行连接起来。 不过,它并没有真正按预期工作。

这是我目前得到的:

import re

with open('Rapp.txt', 'r') as f:

 for line in f:
  previous = line #keep current line in variable to join next line
  if not re.match(r'^[A-Za-z]{3}', line): #regex to match 3 letters
   print(previous.join(line)) 

脚本显示没有输出只是默默地完成,有什么想法吗?

最佳答案

我想我会采取稍微不同的方式:

import re

all_the_data = ""

with open('Rapp.txt', 'r') as f:
    for line in f:
        if not re.search("\d{4}-\d{1,2}-\d{1,2};\n", line):
            line = re.sub("\n", "", line)
        all_the_data = "".join([all_the_data, line])
print (all_the_data)

有几种方法可以做到这一点,各有利弊,但我认为这很简单。

如果该行没有以日期结尾,则按照您所做的那样循环文件;把回车去掉,塞进all_the_data。这样你就不必再回头看文件了。同样,有很多方法可以做到这一点。如果您更愿意使用以 3 个字母和一个 ; 开头的逻辑回过头来看,这是可行的:

import re

all_the_data = ""

with open('Rapp.txt', 'r') as f:
    all_the_data = ""
    for line in f:
        if not re.search("^[A-Za-z]{3};", line):
            all_the_data = re.sub("\n$", "", all_the_data)
        all_the_data = "".join([all_the_data, line])

    print ("results:")
    print (all_the_data)

几乎是要求什么。逻辑是如果当前行没有正确开始,从 all_the_data 中取出前一行的回车。

如果您在玩正则表达式本身时需要帮助,这个网站很棒:http://regex101.com

关于python - 根据第一列中的字母数将行与上一行连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47535168/

相关文章:

javascript - Jquery 自定义验证非数字

python - kivy按钮文本=""逻辑错误

regex - 对正则表达式子匹配进行编号

python - 使用tilestache/modestmaps 将wgs84 中的lon/lat 重新投影到目标投影?

python - 如何使DataFrame列长度相等?

python - 我如何使用 pandas 来透视这个基本表?

java - 正则表达式数字范围

python - 您可以将带有参数的函数存储在列表中,然后在 Python 中调用它们吗?

python - 为什么 list(print(x.upper(), end =' ' ) for x in 'spam' ) 得到一个 [None, None, None, None] 列表?

python - 如何求定义有两点的矩形的面积和周长?