【问题标题】:Parse text file from web site to .csv file将文本文件从网站解析为 .csv 文件
【发布时间】:2015-08-07 03:15:43
【问题描述】:

我需要将 .txt 文件解析为 .csv 文件。要解析的数据看起来像以下三行一遍又一遍,直到文件末尾。

俄克拉荷马-07 (rt66) 1 12345k 9876542、4234234.5345345 -.000001234 0000.0 14135.4 0 9992 2 12345 101.8464 192.3456 00116622 202.9136 512.3361 12.543645782334 德州 15 (hwy35) 1 12345k 9876542、4234234.5345345 -.000001234 0000.0 14135.4 0 9992 2 12345 101.8464 192.3456 00116622 202.9136 512.3361 12.543645782334

上面的分隔符是空格。

源文件也将来自一个网站,我将信息保存在一个网站上,它是一个 .txt 文件,目前显示在屏幕上。例如。看起来像“http://www.example.com/listing.txt”。

可能只有前 3 行或 90 或 144 行数据,但数据总是在三行中,然后是下一个数据集。它只需要将文件解析到文件末尾。

总是有两个关键字符:

"1" 在第二行,并且 数据集第三行的“2”

并且输出需要解析如下:

oklahoma-07,(rt66), 1, 12345k, 9876542, 4234234.5345345, -.000001234, 0000.0, 14135.4, 0, 9992, 2, 12345, 101.8464, 192.3456, 00116622, 202.9136, 512.3361, 12.543645782334

texas-15, (hwy35), 1, 12345k, 9876542, 4234234.5345345, -.000001234, 0000.0, 14135.4, 0, 9992, 2, 12345, 101.8464, 192.3456, 00116622, 202.9136, 512.3361, 12.543645782334

所以我可以在 Excel 中查看它,分隔符应该是逗号。为简单起见,我对每个数据集使用了相同的数字。

最后,我需要将文件保存到特定位置的 filename.csv 文件中,例如C:/documents/stuff/.

我对 Python 完全陌生。我看过很多不同的代码示例,这让我很困惑。

【问题讨论】:

  • 每行之间是否有空行,或者它们都一起运行?

标签: python parsing csv


【解决方案1】:

如果您确定数据将始终采用这种格式,一个简单的方法是这样的:

comma_sep = []
this_line = []

lines = my_file.readlines()

for i in range(len(lines)):
    if i % 3 = 0:
        comma_sep.append(" ".join(this_line))
        this_line = []
    else:
        this_line.append(lines[i])

for line in comma_sep:
    line.replace(' ',',')

我确信有一种更清洁的方法。

另外,我建议阅读 Python 文档以获取基本信息,例如如何使用 urllib 和文件处理。

【讨论】:

    【解决方案2】:

    这是一种方法,包括如何下载txt文件和写入csv文件。块生成器代码来自this answer.

    import urllib2
    
    inputfile = urllib2.urlopen('http://127.0.0.1:8000/data.txt')
    lines = inputfile.readlines()
    
    def chunks(l, n):
      """Yield successive n-sized chunks from l."""
      for i in xrange(0, len(l), n):
        yield l[i:i+n]
    
    out = []
    for record in chunks(lines, 4):
      s = ' '.join(record).replace(',','') # Create a string from the record (list) and remove the comma
      out.append(','.join(s.split())) # Creates a comma separated string and removes whitespace
    
    with open('data.csv', 'w') as outfile:
      for record in out:
        outfile.write("%s\n" % record)
    

    【讨论】:

    • 添加了下载txt文件的代码,而不是从磁盘打开它(非常相似)
    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2017-10-26
    • 1970-01-01
    相关资源
    最近更新 更多