简体   繁体   English

如何将拆分文本保存到excel文件?

[英]How to save split text into excel file?

I have an excel file containing a column of text with special characters such as the following: 我有一个excel文件,其中包含一列带有特殊字符的文本,如下所示:

Hi, My name is : Sam : and I live in : New York:
Hi, My name is : Samantha : and I live in : New Jersey:
Hi, My name is : John : and I live in : England:
Hi, My name is : Samuel : and I live in : India:

and i want to separate each rows of text by the separator colon separator ":" and this would give me two text one "Sam" and the other "New York". 我想通过分隔符冒号“:”分隔每行文本,这将给我两个文本一个“Sam”和另一个“纽约”。 How do i save these two items in a separate excel file after separating each lines of rows? 在分隔每行后,如何将这两个项目保存在单独的Excel文件中?

First, i have tried to save the column into a list and use the for loop to go through each rows to separate the text on each rows. 首先,我试图将列保存到列表中,并使用for循环遍历每一行以分隔每行上的文本。 These has worked to separate each rows by the delimiter ":" however i am having problem saving the separated text 这些已经通过分隔符“:”分隔每一行,但是我在保存分隔文本时遇到问题

l = 0
for i in range(0,2):
    print(infolist[l].split(sep=':'))
    l+=1

Assuming you have the initial code block saved as a .csv file you can do this pretty easily: 假设您将初始代码块保存为.csv文件,您可以非常轻松地执行此操作:

import csv

with open('test.csv', 'r') as file:
    my_reader = csv.reader(file, delimiter=':')
    for row in my_reader:
        print(row)

Where you specify the ":" as a delimiter 在哪里指定“:”作为分隔符

Output: 输出:

['Hi, My name is ', ' Sam ', ' and I live in ', ' New York', '']
['Hi, My name is ', ' Samantha ', ' and I live in ', ' New Jersey', '']
['Hi, My name is ', ' John ', ' and I live in ', ' England', '']
['Hi, My name is ', ' Samuel ', ' and I live in ', ' India', '']

I believe it would work with other file extensions as well and you just need to change 'test.csv' to your file name. 我相信它也适用于其他文件扩展名,你只需要将'test.csv'更改为你的文件名。 Additionally csv comes standard with python so there is no need to pip install anything! 另外csv标配python,所以不需要pip install任何东西!

If this isn't what you were asking I think you need to rephrase your question and be more specific 如果这不是您所问的问题,我认为您需要重新解释您的问题并更具体

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

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