从Python中的制表符分隔文本文件提取第i列。

huangapple go评论71阅读模式
英文:

Extracting i-th column from a tab separated text file in python

问题

You can achieve this in Python by reading the text file, splitting each line by tabs, and then extracting the 3rd column. Here's the code:

# Open the text file
with open('your_file.txt', 'r') as file:
    # Read each line
    for line in file:
        # Split the line by tabs
        data = line.strip().split('\t')
        # Extract and print the 3rd column (index 2)
        if len(data) > 2:
            print(data[2])

Replace 'your_file.txt' with the actual file path where your data is located. This code will read the file, split the lines by tabs, and print the 3rd column containing the country names.

英文:

Say, I have a text file like this

John 32 Britain Marry Sunny
Britney 21 India Angel Cloudy
Jack 22 UK Becky Snowy
Jill 43 United States of America Bill Cloudy
Amy 31 South Africa Claudey Sunny

The data is tab separated. I want to extract the 3rd column which has the country names in a text file

Britain
India
UK
United States of America
South Africa

How to do this using python? Any help will be great. 从Python中的制表符分隔文本文件提取第i列。

答案1

得分: 1

你可以使用标准库中的 csv 模块。示例实现:

import csv

rows = []
with open(PATH_TO_CSV) as f:
    for row in csv.reader(f, delimiter="\t"):
        rows.append(row)

countries = [row[2] for row in rows]
英文:

You can use the csv module from the standard library. Example implementation:

import csv

rows = []
with open(PATH_TO_CSV) as f:
    for row in csv.reader(f, delimiter="\t"):
        rows.append(row)

countries = [row[2] for row in rows]

huangapple
  • 本文由 发表于 2023年4月10日 19:32:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定