从json文件中提取了特定字段的句子,存入了一个list,需要对这个list中的句子做特定规则的分词操作。
一些句子中中间存在空格,
1. 用第一种方法取stepdes_list中的句子,取出的句子的type仍然是list,不能用str的strip()方法去掉前后的空格,且也不能去掉中间的空格,因此按循环的方式处理,代码见下:
# list的方法取出句子 for i in range(len(stepdes_list)): if stepdes_list[i].__contains__('点击'): stepdes_list[i] = ps.lcut(stepdes_list[i]) for x in stepdes_list[i]: if x.word in [' ','','“','”','【','】']: stepdes_list[i].remove(x) preList.append(stepdes_list[i])
在这段代码中,stepdes_list[i]是class<list>的类型。
遍历句子中的每个单词,如果是空格或者我需要删除的指定符号,就移除。存在的问题是,这种移除方式并没有移除一个句子首尾存在的空格。
2.为了移除句子中收尾存在的空格,因此采用第二种方式取stepdes_list中的每个句子:
for sentence in stepdes_list: if sentence.__contains__('点击'): sentence=sentence.strip() sentence = ps.lcut(sentence) for x in sentence: if x.word in [' ','','“','”','【','】']: sentence.remove(x)
用这种for sentence in stepdes_list: 的方式取出的sentence是str类型,因此可以采用str的strip()方法去掉前后的空格,再加上后面循环的方式去掉中间的空格即可。