英文:
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.
答案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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论