【问题标题】:Search for a particular word in a txt file in python在python的txt文件中搜索特定单词
【发布时间】:2016-05-22 11:47:13
【问题描述】:

假设我有一个包含以下信息的 txt 文件:

Name, Score

bob, 3
jack, 8
ben, 4

如何让 python 找到“bob”,并将 bob 的整行复制到变量中?

【问题讨论】:

    标签: python file python-3.x file-io


    【解决方案1】:

    将表读入pandas 数据框并使用pandas 执行查询通常很方便。例如:

    import pandas as pd
    
    # The text file
    txt_file = r'C:\path\to\your\txtfile.txt'
    
    # Read the .txt file into a pandas dataframe
    df = pd.read_table(txt_file, sep = ",")
    
    # Isolate the row based on your query
    row = df.loc[df['Name'] == 'ben']
    

    >>> row
      Name   Score
    2  ben       4
    

    【讨论】:

      【解决方案2】:

      您应该使用csv 模块而不是自定义杂技。

      import csv
      with open(csvfile) as f:
          reader = csv.DictReader(f)
          for row in reader:
              if row['Name'] == 'bob':
                  got = row
                  break
      >>> got
      >>> {' Score': ' 3', 'Name': 'bob'}
      

      你应该把它包装在一个函数中。

      【讨论】:

        【解决方案3】:

        以下代码将以阅读模式打开文件,读取所有行,如果在任何行中找到bob,它将打印整行:

        with open('path_to_your_text_file', 'r') as f:
            lines = f.readlines()
            for line in lines:
                if "bob" in line:
                    print line
        

        【讨论】:

          猜你喜欢
          • 2021-03-17
          • 1970-01-01
          • 2017-08-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-31
          • 2015-09-15
          • 2020-05-05
          相关资源
          最近更新 更多