我想读取'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'])
使用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'])