拆分字符串,unicode,unicode,python中的字符串
问题描述:
我试图拆分python中的字符串unicode组合。必须在从网站检索到的ResultSet对象上进行拆分。使用下面的代码,我能得到的细节,实际上它是用户的详细信息:拆分字符串,unicode,unicode,python中的字符串
from bs4 import BeautifulSoup
import urllib2
import re
url = "http://www.mouthshut.com/vinay_beriwal"
profile_user = urllib2.urlopen(url)
profile_soup = BeautifulSoup(profile_user.read())
usr_dtls = profile_soup.find("div",id=re.compile("_divAboutMe")).find_all('p')
for dt in usr_dtls:
usr_dtls = " ".join(dt.text.split())
print(usr_dtls)
的输出如下:
i love yellow..
Name: Vinay Beriwal
Age: 39 years
Hometown: New Delhi, India
Country: India
Member since: Feb 11, 2016
我需要的是创造不同的5个变量的名称,年龄,家乡,国家,成员自,并在':'之后存储相应的值。
感谢
答
您可以使用dictionary来存储名称 - 值对。例如 -
my_dict = {"Name":"Vinay","Age":21}
在my_dict
,Name
和Age
是字典的键,就可以访问值这样的 - 而且
print (my_dict["Name"]) #This will print Vinay
,很高兴和更好地使用完整的单词作为变量名。
results = profile_soup.find("div",id=re.compile("_divAboutMe")).find_all('p')
user_data={} #dictionary initialization
for result in results:
result = " ".join(result.text.split())
try:
var,value = result.strip().split(':')
user_data[var.strip()]=value.strip()
except:
pass
#If you print the user_data now
print (user_data)
'''
This is what it'll print
{'Age': ' 39 years', 'Country': ' India', 'Hometown': 'New Delhi, India', 'Name': 'Vinay Beriwal', 'Member since': 'Feb 11, 2016'}
'''
答
您可以使用字典来存储你的数据:
my_dict = {}
for dt in usr_dtls:
item = " ".join(dt.text.split())
try:
if ':' in item:
k, v = item.split(':')
my_dict[k.strip()] = v.strip()
except:
pass
注:你不应该使用usr_dtls
您for
循环中,因为这会覆盖原来的usr_dtls