所以我一直在编写一个简单的脚本,从projects主目录中的一个.txt文件中提取股票符号,但我似乎无法让它带回定价数据。如果我手动将它们输入到一个字符串数组中,它是有效的,但是当从文件中提取时,我只是不想返回价格。你知道吗
import urllib
import re
symbolfile = open("symbols.txt")
symbolslist = symbolfile.read()
newsymbolslist = symbolslist.split("\n")
i = 0
while i<len(newsymbollist):
url = "http://finance.yahoo.com/q?uhb=uh3_finance_vert_gs_ctrl1&fr=&type=2button&s=" +symbolslist[i] +""
htmlfile = urllib.urlopen(url)
htmltext = htmlfile.read()
regex = '<span id="yfs_184_' +newsymbolslist[i] +'">(.+?)</span>'
pattern = re.compile(regex)
price = re.findall(pattern,htmltext)
print "The price of", newsymbolslist[i] ," is ", price
i+=1
我真的需要一些帮助,因为它没有给出任何错误的外壳为什么。你知道吗
提前感谢您的帮助!你知道吗
通过实现@Linus Gustav Larsson Thiel在注释中提供的修改和另一个关于
regex
的修改,您的代码将返回正确的结果。请注意正则表达式中的lowercase()
,因为源代码包含小写符号:对于用于测试目的的静态列表
['AAPL','GOOGL','MSFT']
,我收到以下输出:如果需要,还可以简化代码:
for ... in ...
循环消除了对计数器变量的需要,并且由于findall()
返回匹配项列表(而您只需要一个),因此可以附加[0]
以显示包含的字符串,而不是带有单个元素的列表。你知道吗这将返回以下内容:
相关问题 更多 >
编程相关推荐