【问题标题】:searching keyword in text file and printing the entire row在文本文件中搜索关键字并打印整行
【发布时间】:2020-10-04 12:50:09
【问题描述】:

好的,所以我使用了一个 api 并安排了一个如下所示的文本文件:

TITLE,YEAR,IMDB
'Money Plane','2000','tt7286966'
'Mulan','2020','tt4566758'
'Secret Society of Second Born Royals','2020','tt10324122'
'Train to Busan Presents: Peninsula', 'year': '2020', 'imdb_id': 'tt8850222'
'After We Collided','2020','tt10362466'
'One Night in Bangkok','2020','tt12192190'
'Phineas and Ferb The Movie: Candace Against the Universe','2020','tt1817232'
'Cats & Dogs 3: Paws Unite','2020','tt12745164'
'The Crimes That Bind','2020','tt10915060'
'Scoob!','2020','tt3152592'
'We Bare Bears: The Movie','2020','tt10474606'
'Trolls World Tour', 'year': '2020', 'imdb_id': 'tt6587640'
'Birds of Prey (and the Fantabulous Emancipation of One Harley Quinn)','2020','tt7713068'
'Bad Boys for Life','2020','tt1502397'
'Greyhound','2020','tt6048922'
'The Old Guard','2020','tt7556122'
'Sonic the Hedgehog','2020','tt3794354'
'Dad Wanted','2020','tt12721188'
'Barbie: Princess Adventure','2020','tt12767498'
                            

现在我希望能够按标题、年份或 ID 搜索电影

基本上我想这样当我搜索标题时,它会向我显示有关电影的全部详细信息, 例如:搜索木兰,我的输出将是:

'Mulan','2020','tt4566758'

到目前为止,我的代码如下所示:

import pandas


data=pandas.read_csv(r"C:\Users\Home\Documents\studying\newproject\moviedata.txt")
title=list(data["TITLE"])
year=list(data["YEAR"])
imdbid=list(data["IMDB"])

我试过用

for t,y,imdb in zip(title,year,imdbid):
   if word in title:
      items=data[word]
      print(items)

它运行但什么也不做

【问题讨论】:

  • 不要直接问你想要什么,你必须展示你尝试了什么以及你的解决方案中有什么问题。 Visit Here
  • 将csv导入SQLite(stackoverflow.com/questions/2887878/…),使用SQL查询数据。
  • df.loc[df['TITLE'].str.contains('your_key_phrase')] 会做到这一点。我建议学习索引和布尔表达式在 pandas 中的工作原理,它将为您节省很多头痛 :)
  • 好的,但是现在我如何通过 sqlite 进行搜索?

标签: python pandas


【解决方案1】:

您可以在这里使用numpy.where 来查找值,使用pandas loc 来打印行

代码:

import pandas as pd
import numpy as np

df = pd.read_csv('moviedata.txt')

row , col = np.where(df == "'Mulan'")
print(df.loc[row])

输出:

    TITLE   YEAR    IMDB
1   'Mulan' '2020'  'tt4566758'

如果你想以列表的形式输出

row , col = np.where(df == "'Mulan'")
a = df.loc[row]
a = a.values.tolist()
print(a)

输出:

[["'Mulan'", "'2020'", "'tt4566758'"]]

【讨论】:

  • 这真的很有帮助,我不知道你可以用 numpy 做到这一点
  • 但是当我今年做同样的事情时,我得到空数据框
  • @comingfall 今年过得怎么样?请记住,您的所有值都在单个引号中,这应该可以工作:row , col = np.where(df == "'2020'")
  • 我设法通过使用 if 语句解决了这个问题,现在我试图将它插入到列表框中。并在列表框中插入顶部的 TITLE、YEAR、IMDBID。而不是作为数据框
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-14
  • 2014-07-08
  • 2014-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多