如何从python中的文本文件中获取所有3克?

问题描述 投票:0回答:1

我从文本文件中获取了一行,结果它生成了3克的一行,但在行尾,它的输出是2克。例如输入行是cswisceduwwt输出是

csw
swi
wis
isc
sce
ced
edu
dup
upa
par
ara
rad
ady
dyn
yn

在行尾,它生成2克(2个字符)。最后一个克是“yn”,我认为它增加了空间。我不需要“yn”如何删除每行中包含2个字符的最后一个字符?代码如下

def extract_n_grams(line):
        ngram = ngrams(line, 3)
        for item in ngram:
           result=item[0]+item[1]+item[2]
           print(result)

with open('C:/Users/Dania/Desktop/MS 2nd sem/preprocessed.txt') as corpus:
    for line in corpus:
        extract_n_grams(line)
python nlp n-gram
1个回答
0
投票

它显示了最后两个字符,因为它包含空格作为其最后一个(第三个)字符所以我通过使用此语句删除了行尾的空格

for line in corpus:
        rem_line=line.rstrip('\n')  #####removes space at the end of line
        extract_n_grams(rem_line)
© www.soinside.com 2019 - 2024. All rights reserved.