python脚本 - 将单词分组为If-Not语句
试图找出如何使用if语句,在该语句中,我可以将三到四个单词分组,以便从CSV文件中省略。在代码底部,您会看到我卡在:if ('reddit', 'passwords') not in x:
python脚本 - 将单词分组为If-Not语句
任何帮助都会很棒。
# import libraries
import bs4
from urllib2 import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://www.reddit.com/r/NHLStreams/comments/71uhwi/game_thread_sabres_at_maple_leafs_730_pm_et/'
# opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
# html parsing
page_soup = soup(page_html, "html.parser")
filename = "sportstreams.csv"
f = open(filename, "w")
headers = "Sport Links " + "\n"
f.write(headers)
links = page_soup.select("form a[href]")
for link in links:
href = link["href"]
print(href)
f.write(href + "\n")
with open('sportstreams.csv') as f,open('sstream.csv', "w") as f2:
for x in f:
if ('reddit', 'passwords') not in x: # trying to find multi words to omit
f2.write(x.strip()+'\n')
使用内置函数all
:
if all(t not in x for t in ('reddit', 'passwords')):
或者any
:
if not any(t in x for t in ('reddit', 'passwords')):
这是它是在你的情况管理器:
with open('sportstreams.csv') as f, open('sstream.csv', "w") as f2:
for line in f:
if any(t in line for t in ('reddit', 'passwords')):
# The line contains one of the strings.
continue
else:
# The line contains none of the strings.
f2.write(line.strip() + '\n')
这不是我的朋友。我可能做错了什么?我用你写的东西替换了'if('reddit','passwords')不在x:'中。不要忽略包含reddit或密码的行。 :( –
@JamesDean这部分是你自己的错,你的问题中的规格是非常不清楚的 –
我很抱歉,我应该怎样做,以忽略任何包含这些元素的行(reddit,/ r /,/ password)? –
目前还不清楚你想要什么'如果(...)不在x'中做。所有的元素都必须从'x'中丢失,或者它们中的任何一个足以触发'if'? –
我想我的代码很弱,因为我试图用任何包含单词“reddit”“/ r /”和“/ password”的行来简化我的结果以省略。这将缩短我的链接列表,这对我来说是成功的。 :) –
请编辑您的问题的解释,使其完成。如果你能够展示你想要忽略的行与你想要保留的行的具体例子,那将是很好的。 –