2016-12-28 13 views
0

私は、stringの組み合わせを分割しようとしていました。分割は、Webサイトから取得したResultSetオブジェクトで行う必要があります。以下のコードを使用して、私は詳細を取得することができています、実際にはユーザの詳細です:分割文字列、ユニコード、ユニコード、ストリングin 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つの変数を作成することです、Age、Hometown、Country、Member since。 ':'の後に対応する値を格納します。あなたのデータを格納するために辞書を使用することができます

おかげ

答えて

2
をオーバーライドしますので、あなたが、あなたの forループ内 usr_dtlsを使うべきではありません

dictionaryを使用して名前と値のペアを格納できます。例:

my_dict = {"Name":"Vinay","Age":21} 
my_dict

NameAgeは、辞書のキーであり、あなたは、このような値にアクセスすることができます -

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'} 
''' 
0

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

関連する問題