【问题标题】:In python, how can you delete lines in a tabular text format that do NOT contain a specific word?在 python 中,如何删除不包含特定单词的表格文本格式的行?
【发布时间】:2021-12-19 04:27:56
【问题描述】:

我想知道从表格文本中删除行(同时保留标题)的最佳方法是什么,以便只有包含单词的特定条目采用表格格式。

例如,我有一个包含动物及其名称和年龄的表格文本文件。 (标题是动物/名称/年龄。)如何删除所有在“动物”标题中没有“狗”的行?

动物名称年龄

狗皮平 10

狗快乐 14

狗佛罗多 12

猫索伦 11

鸟甘道夫 10

鸟魔多 12

我只想要: 动物名称年龄

狗皮平 10

狗快乐 14

狗佛罗多 12

我的示例代码如下:

import os
headers = 1
field1 = 'ANIMALS'
sep = ' '

def getIndex(delimString, delimiter, name):
    '''Get position of item in a delimited string'''
    delimString = delimString.strip()
    lineList = delimString.split(delimiter)
    index = lineList.index(name)
    return index

infile = 'C:/example'
outfile = 'C:/folder/animals'

try:
    with open(infile, 'r') as fin:
        with open(outfile, 'w') as fout:
            for i in range(headers):
                line = fin.readline()
                fout.write(line)
            line = fin.readline()
            fout.write(line)

            # This is where I get confused, I try using the method below:
            for line in fin:
                lineList = line.split(sep)
                # But the code doesn't work as it only prints the header
                # I have a feeling it's the way I'm phrasing this area
                if field1 == 'DOG':
                    fout.write(line)
            print '{0} created.'.format(outfile)

except IOError:
    print "{0} doesn't exist- send help".format(infile)

在表格 .txt 文件中选择性地打印项目的最佳方法是什么?

【问题讨论】:

  • 它可能只是一个 .txt 文件,也可能是一个 .csv 文件?
  • 在代码中包含数据而不是我们没有的硬编码路径会很有帮助。否则,在包含数据和代码方面做得很好。使用表格格式,您似乎需要空格分隔值和新行分隔记录。
  • 我猜它可以是 txt 或 CSV 文件,都可以。而且我只是在上面的表格文本中使用上面的代码编写一个示例,因为我一直在创建自己的提示。
  • 在您的代码中,您将每一行拆分为lineList,然后继续检查一些变量field1,您将其定义为'ANIMALS' - 因为'ANIMALS' == 'DOG' 永远不是True ,没有写其他行。相反,if lineList[0] == 'DOG': 将是您所追求的。

标签: python file indexing output txt


【解决方案1】:

使用标准输入和标准输出而不是文件来简化它(如果需要,可以将其替换为 open):

import sys

headers = 1
sep = ' '
fin = sys.stdin
fout = sys.stdout
for i in range(headers):
    line = fin.readline()
    fout.write(line)
for line in fin:
    lineList = line.split(sep)
    if lineList[0] == 'Dog':
        fout.write(line)

当你运行它时:

python filter.py < input.txt
Animals Names Ages
Dog Pippin 10
Dog Merry 14
Dog Frodo 12

换句话说,就是不要打印你不想要的东西。

【讨论】:

    【解决方案2】:

    假设它是一个 csv 文件,使用此代码您只能返回具有 Dog as Animals 值的行

    import pandas as pd
    
    df = pd.read_csv(file_name)
    
    df.loc[df.Animals == 'Dog']
    

    如果你想更新文件,你可以运行df.to_csv(filename),它将替换具有相同文件名的 csv 文件,否则它将创建另一个具有文件名的 csv 文件。

    希望对你有所帮助。

    【讨论】:

    • 小任务,大依赖!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多