简体   繁体   English

我想在每行中使用 2 个逗号

[英]I want to get between 2 commas in each line

I want to get between 2 commas in each line.我想在每行中使用 2 个逗号。 My example data.txt like this:我的示例data.txt是这样的:

"",ID SURNAME NAME,1st Midterm
1,9002131225 name1 surname1,90
2,9034623973 name2 surname2,80
3,9082135314 name3 surname3,50

Example output.txt :示例output.txt

9002131225 name1 surname1
9034623973 name2 surname2
9082135314 name3 surname3

how can I do that in python?我怎么能在 python 中做到这一点? thanks.谢谢。

The data format as shown in the example is csv with values ID SURNAME NAME belonging to one column.示例中显示的数据格式为 csv,其值ID SURNAME NAME属于一列。 If you are ok with extra dependency on pandas, then you can:如果您对 pandas 的额外依赖没问题,那么您可以:

import pandas as pd
pd.read_csv("data.txt")['ID SURNAME NAME'].to_csv(
    "output.txt", index=False, header=None)

Or using just string manipulation或仅使用字符串操作

with open("data.txt") as fp:
  txt = fp.read()

with open('output.txt', 'w') as f:
  _ = [f.write(x.split(",")[1]+"\n") for x in txt.split("\n")[1:]]

You can use split(',') in python3 without using any library:您可以在 python3 中使用split(',')而不使用任何库:

string = "1,9002131225 name1 surname1,90"
data = string.split(',')
print(data[1])

output: output:

9002131225 name1 surname1

Read about loops and string manipulation, these are Python basics.阅读有关循环和字符串操作的信息,这些是 Python 基础知识。

A combination of for loop and split() you can do the following:结合使用for 循环split() ,您可以执行以下操作:

with open('data.txt') as f:
    for line in f:
       print(s.split(",")[1])

You should attempt to write code and ask for feedback when you're stuck.当您遇到困难时,您应该尝试编写代码并寻求反馈。

With python capability to read the Input_file, could you please try following, written and tested in Python3.使用 python 读取 Input_file 的能力,您能否尝试在 Python3 中进行以下、编写和测试。 Python program name is scr.py , file from where input is being read is Input_file and program will write output to outputFile . Python 程序名称是scr.py ,从中读取输入的文件是Input_file ,程序会将 output 写入outputFile

cat scr.py
#!/usr/bin/python3
with open('outputFile', 'w') as f_out, open('Input_file') as f_in:
    for line in f_in:
        new_str = "".join(line.split(',')[1:-1])
        f_out.write(new_str + '\n')
    f_out.close()

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

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