每个句子的单词数

0 投票
3 回答
1637 浏览
提问于 2025-04-17 17:44

我正在用Python 2.7读取一个文本文件,我想做的是把每个句子中的单词数量填入一个一维数组里。这里是我现在的代码:

f = open(file_txt, 'r')

sen_prog = []

for line in f:
    sents = line.split('.')
    sen_prog.append(sents)

sen_p = []

for a in sen_prog:
    for b in a:
        sen_p.append(b)

sen_p = numpy.array(sen_p)
sen_p = sen_p[sen_p!='-']

sen_d = []


for c in sen_p:
    sen_d.append([len(x.split()) for x in sen_p])

sen_d = numpy.array(sen_d)
sen_d = numpy.ravel(sen_d)

print sen_prog, sen_d

问题是数组虽然创建了,但句子的数量却不对。我的文本文件里有55个句子(每个句子都是用句号‘.’分开的),但是它给出的数字都是错的……需要帮助!

3 个回答

0

这样做就可以了,并且还可以处理一行中有多个句子的情况:

sen_prog = []
sentence = ''

for line in f:
    parts = line.split('.')
    if len(parts) > 1:
        sentence += parts[0]
        sen_prog.append(sentence)
        if len(parts) > 2:
            sen_prog.append(parts[1:-1])
        sentence = parts[-1]
1

这段代码会生成一个包含句子长度的列表。

with open('path/to/file', 'r') as f:
    l = [len(x.split()) for x in f.read().split('.')]
1

你正在逐行读取文件。假设文件的内容是这样的,其中一句话跨越了多行,这样你可能会得到错误的计数。

This is line 1. This 
is line 2. This is 
line 3.

sen_prog 的值将会是:

[ "This is line 1", "This", "is line 2", "This is", "line 3", ""]

这可能不是你想要的结果。

你可能想要这样做:

sen_prog = " ".join(f.readlines()).split(".")

这样 sen_prog 就是

[ "This is line 1", "This is line 2", "This is line 3", ""]

对于上面的输入。

撰写回答