Given a hotel review as
- "The location is great. Took advantage of the downtown location to walk to dinner, check out a couple galleries, and have drinks. It was great. I highly recommend this hotel for anyone visiting downtown. However, the condition of the rooms were bad. Bed sheets, linens were dirty. Toilet was horrible."
and a list of positive words as
- ['good', 'nice', 'friendly','great', 'clean', 'comfortable', 'amazing', 'enjoyable', 'wonderful', 'great'].
and a list of negative words as
- ['poor', 'bad', 'unfriendly','horrible', 'dirty', 'uncomfortable' ].
Please caculate the percentage of positive words, negative words, and neutral words in this review.
import string txt="The location is great . Took advantage of the downtown location \ to walk to dinner, check out a couple galleries ,\ and have drinks . It was great . I highly recommend this\ hotel for anyone visiting downtown .\ However , the condition of the rooms were bad . Bed sheets ,\ linens were dirty . Toilet was horrible ." for i in txt: if i in string.punctuation: #如果字符是标点符号的话就将其替换为空格 txt = txt.replace(i," ") txt=list(txt.split()) txt_lens=len(txt) positive_list=['good', 'nice', 'friendly','great', 'clean', 'comfortable', 'amazing', 'enjoyable', 'wonderful', 'great'] positive_dict={} negative_list=['poor', 'bad', 'unfriendly','horrible', 'dirty', 'uncomfortable' ] negative_dict={} for i in positive_list: if i in txt: positive_dict.setdefault(i,0) positive_dict[i]+=1 print(positive_dict) pstv=sum(positive_dict.values()) for i in negative_list: if i in txt: negative_dict.setdefault(i,0) negative_dict[i]+=1 print(negative_dict) ngtv=sum(negative_dict.values()) print('the percentage of positive words is :',pstv/txt_lens) print('the percentage of negative words is :',ngtv/txt_lens)
字串符英文标点转空格(03)
最新推荐文章于 2022-08-05 11:32:15 发布