【问题标题】:Splitting a text document into an excel sheet xls将文本文档拆分为 Excel 工作表 xls
【发布时间】:2016-01-03 12:06:31
【问题描述】:

我目前正在尝试将我拥有的文本文档导出/转换为 .xls 文件。因此,根据我的发现,我能够创建一个 xls,但现在我只需要从文本文档中获取正确的 xls 格式。

这是我正在尝试做的一个例子。

假设我有以下文本文档:numbers.txt

|<DOg>|
    |Data1 = 300    |
    |Data2 = 200    |
    |Data3 = 15 |
    |Data4 = 14 |
    |Data5 = 4  |
|<DOg>|
    |Data1 = 800    |
    |Data2 = 500    |
    |Data3 = 25 |
    |Data4 = 10 |
    |Data5 = 5  |

如果我使用| 作为分隔符运行我的代码,我会收到这个 .xls 文件

如您所见,格式已关闭。

我试图达到的目标是以下格式。

我目前使用的代码如下:

mypath = raw_input("Please enter the directory path for the input files: ")

from os import listdir
from os.path import isfile, join
textfiles = [ join(mypath,f) for f in listdir(mypath) if isfile(join(mypath,f)) and '.txt' in  f]

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

import xlwt
import xlrd

style = xlwt.XFStyle()
style.num_format_str = '#,###0.00'

for textfile in textfiles:
    f = open(textfile, 'r+')
    row_list = []
    for row in f:
        row_list.append(row.split('|'))
    column_list = zip(*row_list)
    # for column_list in f:
    #     column_list.append(column.split('|'))
    workbook = xlwt.Workbook()
    worksheet = workbook.add_sheet('Sheet1')
    i = 0
    for column in column_list:
        for item in range(len(column)):
            value = column[item].strip()
            if is_number(value):
                worksheet.write(item, i, float(value), style=style)
            else:
                worksheet.write(item, i, value)
        i+=1
    workbook.save(textfile.replace('.txt', '.xls'))

我的想法是对列使用.split() 方法,但是我不确定如何正确实施,因为当我对列使用split 时,每一行最终都是它自己的列。

【问题讨论】:

    标签: python excel split xlrd xlwt


    【解决方案1】:

    如果我没看错问题,我猜你可以将其转换为逗号分隔格式,从而将其用作 csv 文件。

    >>> for i in f.readlines():
    ...   print i
    ... 
    |Data1 = 300    |
    
    |Data2 = 200    |
    
    |Data3 = 15 |
    
    |Data4 = 14 |
    
    |Data5 = 4  |
    
    |<DOg>|
    
    |Data1 = 800    |
    
    |Data2 = 500    |
    
    |Data3 = 25 |
    
    |Data4 = 10 |
    
    >>> f.seek(0)
    for i in f.readlines():
    ...   if "=" in i:
    ...     "".join(",".join(i.split("=")).split("|")).strip()
    'Data1 , 300'
    'Data2 , 200'
    'Data3 , 15'
    'Data4 , 14'
    'Data5 , 4'
    'Data1 , 800'
    

    您可以修改脚本以将其写入另一个文件,并可能将其格式化为完美的 csv 文件。

    【讨论】:

      【解决方案2】:
      def convert_for_excel(data):
          import re
          with open(data, 'r') as f:
              st = ' '.join(f.readlines())
              li = [x for x in re.split(r'\s*\|',st) if x]
              # find <DOg> indices
              ind_of_dog = [i for i, x in enumerate(li) if x == '<DOg>' ]
              # break the list into sublists by indices of <DOg>
              all_lines = [ li[i:j] for i, j in zip([0]+ind_of_dog, ind_of_dog+[None]) if li[i:j]]
              # zip sublists to make tuples
              # join tuples to make Excel ready strings
              excel_ready = [','.join(t) for t in list(zip(*all_lines)) ]
      
              return excel_ready
      
      
      pprint.pprint(convert_for_excel('data'))
      
      ['<DOg>,<DOg>',
       'Data1 = 300,Data1 = 800',
       'Data2 = 200,Data2 = 500',
       'Data3 = 15,Data3 = 25',
       'Data4 = 14,Data4 = 10',
       'Data5 = 4,Data5 = 5']
      

      【讨论】:

        【解决方案3】:

        您的列似乎是无限的。您需要将所有结果捕获到一个数组中,并将它们转置如下:

        import re
        
        # Strip all spaces and dump all data into an array
        lines = [mo for mo in re.findall('(?s)(?<=\|)([<\w].+?)\s+?\|', open('py.txt').read())]
        # Create an array to hold the transformation
        combined = ['' for x in range(len(lines) / lines.count("<DOg>|"))]
        # Append by rows
        for idx in range(len(lines)):
          combined[idx % len(combined)] += lines[idx] + ','
        
        # Write array to file
        output = open('numbersConverted.csv','w')
        for comb in combined:
          output.write(comb + "\n")
        output.close
        

        这会将您的结果转储到准备导入的 numbersConverted.csv 中。

        【讨论】:

        • 如何编辑or mo in re.findall('(?s)\|(\&lt;DO.*?)\|.*?\|(.*?)\s+\|.*?\|(.*?)\s+\|.*?\|(.*?)\s+\|.*?\|(.*?)\s+\|.*?\|(.*?)\s+\|', all): 行,以便拥有n 个不同的参数?所以假设我有一些带有 6 条数据线的参数和另一个带有 10 条等的参数,我该如何编辑它以允许我打印出每一行
        • 每个数据元素都以重复模式捕获。*?\|(.*?)\s+\|我正好有 5 个。我不认为你会想要这样做 200 次。你只做一次吗?你有几只狗?
        • 使用@LetzerWille,我的解决方案回答了您上面的具体问题,而不是您现在已经澄清的通用解决方案。我试图给出一个简洁的解决方案,但它不会扩展。
        • 我已经更新了我的答案,它更简洁并且可以扩展
        • 这只是一个额外的检查,以确保它以 [] 括号中的内容开头。我已经添加了所有字母,这应该会有所帮助。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-13
        相关资源
        最近更新 更多