从文本文件中提取一列 - Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18323651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract a column from text file - Python
提问by hjames
I'm a beginner py.
我是初学者py。
I need to extract the contents of column 12 from a huge flat text file every time a certain word is found within the text file (similar to awk '{print $12}'
in Bash) in a Python script.
每次awk '{print $12}'
在 Python 脚本的文本文件(类似于Bash)中找到某个单词时,我都需要从巨大的纯文本文件中提取第 12 列的内容。
So far I have (example, not real code):
到目前为止,我有(例如,不是真正的代码):
word = a_word
for a_word in data:
column12 = data.split()
print(column12[11])
I assumed that I should start counting from 0 as opposed to 1, though I very well may be incorrect.
我认为我应该从 0 而不是 1 开始计数,尽管我很可能是不正确的。
Also, is a for
loop correct for this type of code?
另外,for
对于这种类型的代码,循环是否正确?
Thanks!
谢谢!
采纳答案by Martijn Pieters
Loop over the open file object:
循环打开文件对象:
with open('somefile') as infile:
for line in infile:
print(line.split()[11])
So, yes, use a for
loop and use 0-based indexing.
所以,是的,使用for
循环并使用基于 0 的索引。
回答by Madison May
If the columns are text files with delimiter (i.e. space or comma) separated values, you might want to look into python's csv module: http://docs.python.org/2/library/csv.html
如果列是带有分隔符(即空格或逗号)分隔值的文本文件,您可能需要查看 python 的 csv 模块:http: //docs.python.org/2/library/csv.html