【问题标题】:Parsing a CSV file into columns (preferably using python) [closed]将 CSV 文件解析为列(最好使用 python)[关闭]
【发布时间】:2014-06-27 12:32:26
【问题描述】:

我在一个 csv 文件中有很长的名称/句柄/描述列表,我想将其分类为三个不同的列。

数据看起来像这样(每个新行都是 csv 中的另一行):

User  
Adam
@adam
Hi Im Adam

User 
Tom 
@tom 
Astronaut 

...等等(631次)

我想做的是:

 search for the word "User" -> capture the string below "User" (e.g., Adam)
 -> categorize it under a column header called Name
 search for the word "User" -> capture the string 2 below "User"(e.g., @adam)
 -> categorize it under handle
 search for the word "User" -> capture the string 3 below "User"(e.g., Hi Im)
 -> categorize it under description
 break;
 repeat loop 631 times

【问题讨论】:

  • 你有做过什么吗?你遇到过什么问题?我要做的是创建一个类似 [name, tiwtter handle, descprtion] 的列表。循环浏览您的页面并添加到其中。完成后,您可以打印到文件。
  • 投了反对票,因为您只是说出了您想做的事情,而没有展示任何实现它的努力。
  • 道歉。这是我在 stackoverflow 上的第一个问题,但已经使用了数百次该网站 - 如此伟大的社区。我已经尝试了很多东西,但我认为试图解释我所尝试的东西会太混乱/太长。

标签: python parsing csv


【解决方案1】:

您可以使用正则表达式:

txt='''\
User  
Adam
@adam
Hi Im Adam

User 
Tom 
@tom 
Astronaut '''

import re
data=(m.group(1).splitlines() 
          for m in re.finditer(r'^User\s+(.*?)(?=^\s*$|\Z)', txt, re.S | re.M))
print [{k:v.rstrip() 
          for k, v in zip(('Name', 'Handle', 'Comment'), li)} for li in data]

打印:

[{'Comment': 'Hi Im Adam', 'Handle': '@adam', 'Name': 'Adam'}, 
 {'Comment': 'Astronaut', 'Handle': '@tom', 'Name': 'Tom'}]

【讨论】:

    【解决方案2】:

    如果您的文件很大,可以使用基于 chunks 的生成器进行改进,但如果您 100% 确定源文件格式(4 行记录,后跟空格),这将很好地工作:

    def chunks(l, n):
        """ Yield successive n-sized chunks from l.
        """
        for i in xrange(0, len(l), n):
            yield l[i:i+n]
    
    
    with open("test.txt", "r") as fp:
        lines = [x.strip() for x in fp.readlines() if x.strip()]
    
    users = []
    for chunk in chunks(lines, 4):
        users.append({"name": chunk[1], "handle": chunk[2], "message": chunk[3]})
    
    users
    

    返回类似:

    [{'message': 'Hi Im Adam', 'handle': '@adam', 'name': 'Adam'}, {'message': 'Astronaut', 'handle': '@tom', 'name': 'Tom'}]
    

    【讨论】:

    • 嗨,迈克,非常感谢您的回复。 csv 文件实际上缺少一些字段,所以一些记录是 3 行后跟一个空格。但是我尝试了您的代码以尝试理解它,但我得到了“IndexError:list index out of range”。
    【解决方案3】:

    尝试类似:

    for section in open("foo").read().split("User")[1:]:
       user = section.split("\n")
       name = user[1]
       handle = user[2]
       description = user[3]
       print name, handle, description
    

    【讨论】:

    • Nathaniel 非常感谢您的回复。我一直在玩你的代码一段时间了。我喜欢它如何在“用户”之后解析所有内容。它使 .txt 文件成为实际列表。我将“\n”更改为“\r”,但唯一的问题是它返回“字符串索引超出范围”进行描述。我认为是因为它有多个单词....我现在正在努力解决这个问题
    猜你喜欢
    • 2017-11-06
    • 2013-06-21
    • 2013-02-08
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2018-10-01
    • 1970-01-01
    相关资源
    最近更新 更多