【问题标题】:How can i get all 3 grams from a line fetched from a text file in python?如何从 python 中的文本文件中获取的一行中获取所有 3 克?
【发布时间】:2017-12-16 19:53:46
【问题描述】:

我从一个文本文件中提取了一行,结果它生成了 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】:

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

    for line in corpus:
            rem_line=line.rstrip('\n')  #####removes space at the end of line
            extract_n_grams(rem_line)
    

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-16
      • 1970-01-01
      相关资源
      最近更新 更多