简体   繁体   English

在Python中将特定模式从普通文件复制到CSV文件

[英]Copying the specific patterns from normal file to CSV file in Python

If I have data in a file (my.txt) like below: 如果我在文件(my.txt)中有数据,如下所示:

Version 3.1
# fruitstall name
# first-file
* i fruits friutname N 1 name S
* i fruits  friutname N 1  N 
+ x apple
+ y 1
+ z 23
+ a 51
+ x banana
+ y 2
+ z 68
+ a 27
+ x mango
+ y 3
+ z 46
+ a 49 
+ x orange
+ y 4
+ z 15
+ a 54
+ x butterfruit
+ y 5
+ z 76
+ a 86

How can I write this to a CSV file using Python which will be having data like this? 如何使用Python将其写入CSV文件,而该文件将具有此类数据?

apple 1  23 51 
banana 2 68 27
mango 3 46 49
orange 4 15 54
butterfruit 5 76 86

I have tried using this: 我试过使用此:

with open(Unzipped_file_name) as f:
    for line in f:

After this, can you please suggest how to proceed? 在此之后,您能否建议如何进行?

The attached input text in image format as the data above is not formatted properly: 上面数据作为图像格式附加的输入文本格式不正确:

input.jpg input.jpg

The attached output text in image format as the data above is not formatted properly: 上面数据作为图像格式附加的输出文本格式不正确:

output.jpg output.jpg

with open('file.txt') as f:  # open file in read mode
    data = {e: [] for e in ['x', 'y', 'z', 'a']}  # init data dict like this
    data = defaultdict(list)  # or like this. from collections import defaultdict
    for line in f:
        line = line.strip()  # remove new line char
        if line.startswith('+'):  # if line marked with plus
            _, t, v = line.split()  # get 't' (one of x, y, z, a) and v (fruit or num) 
            data[t].append(v)  # append to corresponded list
with open('out.txt', 'w') as f:  # open file in write mode
    for x, y, z, a in zip(data['x'], data['y'], data['z'], data['a']):
        f.write('{} {} {} {}\n'.format(x, y, z, a))
path = 'Path to Text.txt'
file = open(path, "r") 
lines = " ".join(file.readlines()[5:])
lines = lines.split("+ x")
res = []
for i in lines:
    val = filter(None, i.replace("\n", "").replace("+", "").split(" "))
    if val:
        stringVal = val[0]
        for iVal in val[1:]:
            if iVal.isdigit():
                stringVal += " {}".format(iVal)
        res.append(stringVal)
print res

Result: 结果:

['apple 1 23 51', 'banna 2 68 27', 'mango 3 46 49', 'orange 4 15 54', 'butterfruit 5 76 86']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM