【问题标题】:Insert commas after the first and second words in each line using Python?使用 Python 在每行的第一个和第二个单词后插入逗号?
【发布时间】:2021-03-27 17:26:48
【问题描述】:


我有一个 .txt 文件,我需要将其转换为 CSV。
这是我用来转换文件的代码:

import pandas as pd

wb = pd.read_csv('12.txt', encoding='utf-8', delimiter = '،', header = None)

wb.to_csv('12.csv',encoding='utf-8-sig', index = None)

问题是,在每一行中,第一个和第二个单词需要在单独的单元格中,但是它们没有用逗号分隔:

This is an, example, to show, you
The second line, is, the, same
My file contains, thousands of, sentences

如示例所示,只有每行的第一个和第二个单词应该位于单独的单元格中(其他单元格可能包含多个单词!)。 如何使用 Python 仅在每行的第一个和第二个单词后添加逗号?

谢谢

【问题讨论】:

    标签: python regex csv text nlp


    【解决方案1】:

    如果您的目标是让每个单词位于不同的单元格中,您可以将以下内容应用于每一行:

    line = "This is an, example, to, show, you"
    
    split = line.split(",")
    
    x = [item for sublist in [k.split(" ") for k in s] for item in sublist]
    y = list(filter(lambda x: x != "", x))
    
    output: ['This', 'is', 'an', 'example', 'to', 'show', 'you']
    

    【讨论】:

      【解决方案2】:

      我会在这里使用str.replace

      wb['col'] = wb['col'].str.replace('^(\S+) (\S+)', '\1, \2,')
      

      【讨论】:

      • 谢谢。我不应该在这行之前定义“col”吗?
      • 我假设你已经有一个列col,你只是想覆盖它。
      猜你喜欢
      • 1970-01-01
      • 2021-06-12
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 2017-02-26
      • 2019-07-12
      相关资源
      最近更新 更多