【问题标题】:How do I read a csv value with an If then statement?如何使用 If then 语句读取 csv 值?
【发布时间】:2018-03-04 10:58:04
【问题描述】:

我想读取 'Rel volume' 的 csv 文件值,然后在值为 2.5 或更大时打印代码和值。但是,我不能这样做,因为 int 值无法与“str”值进行比较。如何比较这些值,然后将 csv 文件的值从相应的股票代码放入一个新列表中? 这是我的代码:

import csv
import urllib.request
from bs4 import BeautifulSoup


write_header = True

twiturl = "https://twitter.com/ACInvestorBlog"
twitpage = urllib.request.urlopen(twiturl)
soup = BeautifulSoup(twitpage,"html.parser")

print(soup.title.text)

tweets = [i.text for i in soup.select('a.twitter-cashtag.pretty-link.js-nav b')]
""""
print(tweets)
"""
URL_BASE = "https://finviz.com/quote.ashx?t="

with open('_Stocks.csv', 'w', newline='') as file:
    writer = csv.writer(file)

    # note the change
    for tckr in tweets:
        URL = URL_BASE + tckr
        try:
            fpage = urllib.request.urlopen(URL)
            fsoup = BeautifulSoup(fpage, 'html.parser')

            if write_header:
                # note the change
                writer.writerow(['tckr'] + list(map(lambda e: e.text, fsoup.find_all('td', {'class': 'snapshot-td2-cp'}))))
                write_header = False

            # note the change
            writer.writerow([tckr] + list(map(lambda e: e.text, fsoup.find_all('td', {'class': 'snapshot-td2'}))))
        except urllib.request.HTTPError:
            print("{} - not found".format(URL))

with open('_Stocks.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file)

    for line in csv_reader:
        if line['Rel Volume'] > 2.5:
            print(line['tckr'], line['Rel Volume'])

【问题讨论】:

  • 您是否尝试过将值转换为数字?
  • 请注意,with open(...) as csv_file: 行之前的所有内容都与问题无关,可以安全地删除。您可以仅使用最后 6 行来重现您的问题。
  • 它应该适用于 float(line[. . .]) > 2.5。也只需使用 pandas 加载 pandas 来加载您的 csv 文件。它比在线条上循环要优雅得多。
  • 感谢@dennis-ec 的帮助

标签: python csv


【解决方案1】:

使用csv.DictReader()读取数据时,值都是字符串。因此,您需要在使用 Rel Volume 之前将其转换为浮点数:

with open('_Stocks.csv', newline='') as csv_file:
    csv_reader = csv.DictReader(csv_file)

    for line in csv_reader:
        line['Rel Volume'] = float(line['Rel Volume'])

        if line['Rel Volume'] > 2.5:
            print(line['tckr'], line['Rel Volume'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多