(0, u'0.559*"delivery" + 0.124*"area" + 0.018*"mile" + 0.016*"option" + 0.012*"partner" + 0.011*"traffic" + 0.011*"hub" + 0.011*"thanks" + 0.010*"city" + 0.009*"way"')
(1, u'0.397*"package" + 0.073*"address" + 0.055*"time" + 0.047*"customer" + 0.045*"apartment" + 0.037*"delivery" + 0.031*"number" + 0.026*"item" + 0.021*"support" + 0.018*"door"')
(2, u'0.190*"time" + 0.127*"order" + 0.113*"minute" + 0.075*"pickup" + 0.074*"restaurant" + 0.031*"food" + 0.027*"support" + 0.027*"delivery" + 0.026*"pick" + 0.018*"min"')
(3, u'0.072*"code" + 0.067*"gps" + 0.053*"map" + 0.050*"street" + 0.047*"building" + 0.043*"address" + 0.042*"navigation" + 0.039*"access" + 0.035*"point" + 0.028*"gate"')
如何从上面的每个元组中提取前三个单词(基于旁边的数字)?
OUTPUT应为:
(0,delivery area mile)
(1,package address time)
(2,time order minute)
(3, code gps map)
答案 0 :(得分:1)
使用re.findall()
和str.join()
函数的解决方案:
import re
l = [
(0, u'0.559*"delivery" + 0.124*"area" + 0.018*"mile" + 0.016*"option" + 0.012*"partner" + 0.011*"traffic" + 0.011*"hub" + 0.011*"thanks" + 0.010*"city" + 0.009*"way"'),
(1, u'0.397*"package" + 0.073*"address" + 0.055*"time" + 0.047*"customer" + 0.045*"apartment" + 0.037*"delivery" + 0.031*"number" + 0.026*"item" + 0.021*"support" + 0.018*"door"'),
(2, u'0.190*"time" + 0.127*"order" + 0.113*"minute" + 0.075*"pickup" + 0.074*"restaurant" + 0.031*"food" + 0.027*"support" + 0.027*"delivery" + 0.026*"pick" + 0.018*"min"'),
(3, u'0.072*"code" + 0.067*"gps" + 0.053*"map" + 0.050*"street" + 0.047*"building" + 0.043*"address" + 0.042*"navigation" + 0.039*"access" + 0.035*"point" + 0.028*"gate"')
]
result = [tuple([t[0], ' '.join(re.findall(r'"([a-z]+)"', t[1])[0:3])]) for t in l]
print(result)
输出:
[(0, 'delivery area mile'), (1, 'package address time'), (2, 'time order minute'), (3, 'code gps map')]
答案 1 :(得分:1)
我会:
" + "
分割创建元组(系数,值)(如果空格数有所不同,可能需要正则表达式),然后根据"*"
在(复杂的)单行中:
l = [(0, u'0.124*"area" + 0.018*"mile" + 0.016*"option" + 0.012*"partner" + 0.011*"traffic" + 0.011*"hub" + 0.011*"thanks" + 0.559*"delivery" + 0.010*"city" + 0.009*"way"'),
(1, u'0.073*"address" + 0.055*"time" + 0.397*"package" + 0.047*"customer" + 0.045*"apartment" + 0.037*"delivery" + 0.031*"number" + 0.026*"item" + 0.021*"support" + 0.018*"door"'),
(2, u'0.190*"time" + 0.127*"order" + 0.113*"minute" + 0.075*"pickup" + 0.074*"restaurant" + 0.031*"food" + 0.027*"support" + 0.027*"delivery" + 0.026*"pick" + 0.018*"min"'),
(3, u'0.047*"building" + 0.072*"code" + 0.067*"gps" + 0.053*"map" + 0.050*"street" + 0.043*"address" + 0.042*"navigation" + 0.039*"access" + 0.035*"point" + 0.028*"gate"')]
result = [" ".join(x[1].strip('"') for x in sorted((e.split("*") for e in sl[1].split(" + ")),key=lambda x:float(x[0]),reverse=True)[:3]) for sl in l]
print(result)
结果:
['delivery area mile', 'package address time', 'time order minute', 'code gps map']
(请注意,我已经改组了测试系数排序的项目顺序)