我有一个清单:
my_list = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
我如何删除\t
和之后的所有内容以获得此结果:
['element1', 'element2', 'element3']
Answers:
就像是:
>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']
不要将list用作变量名。您也可以查看以下代码:
clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]
或就地编辑:
for i,x in enumerate(clist):
if '\t' in x:
clist[i] = x[:x.index('\t')]
我不得不将特征提取列表分为两部分:lt,lc:
ltexts = ((df4.ix[0:,[3,7]]).values).tolist()
random.shuffle(ltexts)
featsets = [(act_features((lt)),lc)
for lc, lt in ltexts]
def act_features(atext):
features = {}
for word in nltk.word_tokenize(atext):
features['cont({})'.format(word.lower())]=True
return features