Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python:读取数据文件并处理/过滤数据_Python 3.x - Fatal编程技术网

Python 3.x Python:读取数据文件并处理/过滤数据

Python 3.x Python:读取数据文件并处理/过滤数据,python-3.x,Python 3.x,我最近开始学习Python,试图抓住概念,同时获得了一个30K行的示例数据文件,如下所示,用空格分隔 P160543 East Asia and Pacific IN C P166720 Africa IN N P165276 East Asia and Pacific AD n IIST P159835 Latin America and Caribbean LA B P160778 Latin America and Caribbean LA B

我最近开始学习Python,试图抓住概念,同时获得了一个30K行的示例数据文件,如下所示,用空格分隔

P160543 East Asia and Pacific   IN  C   
P166720 Africa  IN  N   
P165276 East Asia and Pacific   AD  n   IIST
P159835 Latin America and Caribbean LA  B   
P160778 Latin America and Caribbean LA  B   
P164290 South Asia  AS  N   
P165493 South Asia  SA  N   
P165585 Latin America and Caribbean LAC N   
P157987 South Asia  SA  C   ALAESH
P158364 South Asia  SAS B   EPATET
  • 需要跳过第4列中包含“N”或“N”的行:

  • 现在读取每一行并将列的值保存在变量中

  • 如果Typest='IN',请指定搜索,然后将值作为RegionName返回 ='East Asia and Pacific'和'Africa'和id=P160543、P166720
  • 如果列3='AD',则从列2='East Asia and Pacific'返回值,id=P165276 如果Colum3='LAC',则返回值拉丁美洲和加勒比

    我没有Numpy和其他库可供使用。。。希望通过文件概念完成此操作

    我知道如何读取文件并显示文件内容,删除空行并跳过注释行,但仍停留在上述问题上


    请给出建议。

    创建一个生成器以循环文件的行 从文件的第一行获取标题

    def read_file(fullname):
        with open(fullname) as f:
            for line in f:
                yield header_line, line
    


    这应该足够让你开始了,因为这闻起来像是家庭作业


    小心任何推荐pandas的人-我在大数据环境中工作,pandas不工作,而多gig文件/数百万记录生成器将工作。

    删除了列标题。。。刚刚意识到文件没有标题行fyi(其他人回答):header\u line=“id RegionName TypeSt TypePD TypeCode”谢谢Schalton。抱歉,我已从文件中删除标题行。。。刚刚意识到文件没有标题行来标识列名称。您可以从生成器中删除标题索引,并在循环外部设置标题字符串或列表。这应该足以让您继续。如果您正在寻找一个完全编码的解决方案,请跳到第五页:-D
    myFile = read_file(r"Path/To/Your/File")
    header_line = "id    RegionName    TypeSt    TypePD    TypeCode"
    
    for line in myFile:
        data = dict(zip(header.split("\t"), line.split("\t")))
    
        # Here's a dictionary of the data for the current row
        # You can access the elements of the row by name as follows in the filter example:
    
        if data["TypePD"].lower() == "N":
            continue
        .....