我正在编写一个使用beautifulsoup解析weather.com站点并打印天气的程序。在分析要打印的位置时,会打印一个不需要的单词:
今天,在不列颠哥伦比亚省的伯纳比,外面的天气部分是阴云密布,10°。
不列颠哥伦比亚省之后的‘天气’是不受欢迎的。我如何从课堂上只刮掉课文的一部分?
相关代码:
current_temperature = soup.find(class_="CurrentConditions--tempValue--3KcTQ").text
current_state = soup.find(class_="CurrentConditions--phraseValue--2xXSr").text
current_location = soup.find(class_="CurrentConditions--location--1Ayv3").text
string = "\nToday in " + current_location + ", the weather outside is " + current_state + ", at " + current_temperature + "\n"
print(string)全输出:
今天在不列颠哥伦比亚省伯纳比,外面的天气部分是阴云密布,10°。
提前感谢您的帮助
发布于 2021-05-20 05:44:34
如果这是常见的情况,您可以尝试一种蛮力方法:
current_location = soup.find(class_="CurrentConditions--location--1Ayv3").text
current_location = current_location[:current_location.find(" Weather")]发布于 2021-05-20 05:45:50
x = string.replace('Weather ','')
print(x)发布于 2021-05-20 07:07:38
最方便的方法是将字符串完全替换为"“。
string.replace(" Weather", "")记住在天气前添加一个空格,因为你不需要这个空间。
https://stackoverflow.com/questions/67614576
复制相似问题