首页 > 解决方案 > 如何从 Python 中的 readlines 列表中选择一个项目?

问题描述

所以这就是我到目前为止的一个班级项目

import os 

UserSelection = input("Select a txt file: ")

with open(UserSelection, 'r', encoding= "latin-1") as f:
    lines= f.readlines()


    print("These are your headers:", lines[0])

state = words()[6]

for i in range(1,len(lines)):
    words=line.split
       if(words()[6] == 'California'):
        print(lines)

我有一个很大的人口普查表,我试图只保留 STATE(即第 6 个索引)为 CA 的行。我以为 words()[6]会这样做,但事实并非如此。提前谢谢!

标签: pythonpython-3.xlistreadlines

解决方案


欢迎来到 SO。在您发布的代码中,有几行不太清楚理解。
1)print("These are your headers:", lines[0])没有正确缩进。
2)state = words()[6]在此行之前没有定义单词。
3)for i in range(1,len(lines)):在这一行中,您正在迭代行索引,而第一行可以替换为line in lines[1>]:.
4)words=line.split列表中的 split 方法在 python 中是可调用的,所以在使用该方法时应该使用 ()。
5)if(words()[6] == 'California'):与拆分词不同的是,它是变量而不是方法,因此不应使用 () 调用它。
我理解的代码应该是代码的方式更像

import os 

userSelection = input("Select a txt file: ")

with open(userSelection ,'r', encoding= "latin-1") as f:
    lines= f.readlines()

print("These are your headers:", lines[0])

for line in lines[1:]:
    words=line.split()
    if words[6] == 'California':
        print(lines)

推荐阅读