csv 如何在Python中替换文本中特定位置前后的所有字符

j91ykkif  于 2023-06-27  发布在  Python
关注(0)|答案(1)|浏览(110)

我有一个csv文件与分隔符在文本列。文本列中分隔符的数量因行而异。
csv数据示例(分隔符为“_”):ID_GROUP_TEXT_DATE_PART 101_group_1_Some text is here_23.06.2023_1 102_group_2_Some text is _here_23.06.2023_1 103_group_3_Some text _ is _here_23.06.2023_1 104_group_4_Some text is here_23.06.2023_1
我想按列正确地分割文本。预期结果是:
| ID|联系我们|正文|日期|部分|
| - -----|- -----|- -----|- -----|- -----|
| 一百零一|组_1|一些文本在这里|23.06.2023|一个|
| 一百零二|组_2|一些文本在这里|23.06.2023|一个|
| 一百零三|第三组|这里有一些文本|23.06.2023|一个|
| 一百零四|组_4|一些文本在这里|23.06.2023|一个|

ht4b089n

ht4b089n1#

我建议编写一个RegEx模式来查找相应的列。
在你的例子中,你应该创建一个模式,如下所示:Number_group_n_text_date_Number
所以最终代码应该是:

import re
import pandas as pd

data = """
101_group_1_Some text is here_23.06.2023_1
102_group_2_Some text is _ here_23.06.2023_1
103_group_3_Some text _ is _ here_23.06.2023_1
104_group_4_Some text is here_23.06.2023_1
"""

pattern = r"(\d+)_group_(\d+)_(.+)_(\d{2}.\d{2}.\d{4})_(\d)"

matches = re.findall(pattern, data)

df = pd.DataFrame(matches, columns=['ID', 'GROUP', 'TEXT', 'DATE', 'PART'])

print(df)

相关问题