【问题标题】:loop through results looking for a string using python使用python循环查找字符串的结果
【发布时间】:2015-06-23 14:05:07
【问题描述】:

我有一个 csv,我想找到每次出现的“http://”。使用下面的代码我什么也没得到。在这一点上,我想知道为什么我根本没有得到任何结果(甚至没有打印'hi')。我是一个菜鸟,这对我来说没有意义。欢迎解释,链接很好,但前提是它们可以帮助我理解......

import csv

with open('a_bunch_of_urls_and_other_stuff.csv', 'rb') as f:
    reader = csv.reader(f, delimiter=',')

    # remove results that dont have 'http://'     
    for result in reader:
        # print result      # this prints everything from the cvs
        # print result[2]   # this prints out the column with urls

        if result[2] == 'http://':
           print 'hi'

【问题讨论】:

  • 您似乎想使用if "http://" in result[2]。例如。使用search_term in result[2] 而不是search_term == result[2]。如果您认为将来您可能还会关心 https:// 或其他协议,您可能还想考虑使用正则表达式。
  • 你得给我们一些东西继续下去!对于某些行,print result[2] 看起来像什么?测试应该是if result[2].lower().startswith('http://'):吗?
  • 基本上,我想“检查”以查看行中是否有“http://”。如果是,则打印...如果不是,则不要打印。

标签: python csv if-statement for-loop


【解决方案1】:

我假设您尝试检查结果 [2] 是否包含“http://”。
你可以试试:

if "http://" in result[2]:
    print result[2]

【讨论】:

  • if result[2] == 'http://':检查 result[2] 的内容是否正好是 'http://'。我的答案是检查结果 [2] 是否至少有一个值为“http://”的子字符串。
猜你喜欢
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多