我是python的初学者,很难弄清楚我的代码有什么问题。你知道吗
我在这里要做的是将文本转换为列表中的元组,然后计算列表中的dt数。你知道吗
假设txt文件的前三行如下所示:
The/DT Fulton/NNP County/NNP Grand/NNP Jury/NNP said/VBD Friday/NNP an/DT investigation/NN of/IN Atlanta/NNP 's/POS recent/JJ primary/JJ election/NN produced/VBD ``/`` no/DT evidence/NN ''/'' that/IN any/DT irregularities/NNS took/VBD place/NN ./.
The/DT jury/NN further/RB said/VBD in/IN term-end/JJ presentments/NNS that/IN the/DT City/NNP Executive/NNP Committee/NNP ,/, which/WDT had/VBD over-all/JJ charge/NN of/IN the/DT election/NN ,/, ``/`` deserves/VBZ the/DT praise/NN and/CC thanks/NNS of/IN the/DT City/NNP of/IN Atlanta/NNP ''/'' for/IN the/DT manner/NN in/IN which/WDT the/DT election/NN was/VBD conducted/VBN ./.
The/DT September-October/NNP term/NN jury/NN had/VBD been/VBN charged/VBN by/IN Fulton/NNP Superior/NNP Court/NNP Judge/NNP Durwood/NNP Pye/NNP to/TO investigate/VB reports/NNS of/IN possible/JJ ``/`` irregularities/NNS ''/'' in/IN the/DT hard-fought/JJ primary/NN which/WDT was/VBD won/VBN by/IN Mayor-nominate/NNP Ivan/NNP Allen/NNP Jr./NNP ./.
保存为“练习.txt“在工作区中。你知道吗
所以我的代码如下:
with open("practice.txt") as myfile:
for line in myfile:
cnt += 1
word = line.split()
total_word_per_line += len(word)
total_type_of_words += len(set(word))
a = [tuple(i.split('/')) for i in word]
for x in a:
DT_sum = 0
if x[1] == 'DT':
DT_sum += 1
total_DT_sum += DT_sum
print total_DT_sum
但是输出显示2表示total_DT_sum,这意味着它只在第三个列表中计算DT。有没有建议把所有的DTs都算上?你知道吗
期望的输出是5(上面三句话的DT总数)
提前谢谢!你知道吗
您的错误:
DT_sum
每次都重置为0。。。你知道吗如果您想从头开始,最简单的方法是在每一行上使用
sum
的count
:结果是13,而不是您所说的5(可以手动验证)
这个解决方案没有考虑到分词。这意味着它也会找到
/DTXXX
,如果有的话。你知道吗所以更复杂一点的代码可以做到:
每次计数1根据
/
拆分,每行的每个单词的右边都有DT
。你知道吗如果需要在计算} 如下所示:
'DT'
个数之前将数据存储在元组列表中,可以使用^{^{} 用于将每行的构造元组添加到
my_list
^{} 将只返回
'DT'
位于第二个位置的项。你知道吗输出:
相关问题 更多 >
编程相关推荐