我在这里要做的基本上是让regex根据Python创建和编写的文本文件的模式返回我想要的匹配。你知道吗
目前我得到TypeError: 'NoneType' object is not iterable
错误,我不知道为什么。如果我需要更多的信息,请告诉我。你知道吗
#Opens Temp file
TrueURL = open("TrueURL_tmp.txt","w+")
#Reviews Data grabbed from BeautifulSoup and write urls to file
for link in g_data:
TrueURL.write(link.get("href") + '\n')
#Creates Regex Pattern for TrueURL_tmp
pattern = re.compile(r'thread/.*/*apple|thread/.*/*potato')
search_pattern = re.search(pattern, str(TrueURL))
#Uses Regex Pattern against TrueURL_tmp file.
for url in search_pattern:
print (url)
#Closes and deletes file
TrueURL.close()
os.remove("TrueURL_tmp.txt")
您的搜索没有返回匹配,因为您是在
str
表示的file object
上进行搜索的,而不是实际的文件内容。你知道吗您基本上是在搜索以下内容:
如果要搜索文件内容,请关闭该文件,以便明确写入内容,然后重新打开并读取行,或者只在循环中搜索
for link in g_data:
如果确实要写入临时文件,请使用临时文件:
search_pattern
是一个_sre.SRE_Match object
,所以您可以称为组i,eprint(search_pattern.group())
,或者您想使用findAll。你知道吗我仍然认为在你写任何东西之前做搜索可能是最好的方法,也许根本不写,但我不完全确定你到底想做什么,因为我看不出文件如何适合你正在做的事情,连接到一个字符串将达到同样的效果。你知道吗
这是我找到的答案来回答我原来的问题,虽然Padraic的方法是正确的,不那么痛苦的过程。你知道吗
相关问题 更多 >
编程相关推荐