Python - 仅在特定情况下读取文件的最后一行

时间:2016-10-28 10:30:00

标签: python json for-loop twitter readline

我正在尝试使用Python处理一些推文,而我正试图对7种不同推文中包含的最流行的单词进行字数统计。我有我的文件设置,每个推文都是一个JSON对象在自己的行上,当我尝试使用以下内容打印每个推文时,它完美地工作:

with open(fname, 'r') as f:
for line in f:
    tweet = json.loads(line) # load it as Python dict
    print(json.dumps(tweet, indent=4))

然而,当我尝试在我的单词计数中做类似的事情时,它要么读取文件的最后一行7次,要么只读取文件的最后一行一次。我使用以下代码,从结果中删除停用词:

with open(fname, 'r', encoding='utf8') as f:
count_all = Counter()
# Create a list with all the terms
terms_stop = [term for term in tokens if term not in stop]
for line in f:
    # Update the counter
    count_all.update(terms_stop)
# Print the first 5 most frequent words
print(count_all.most_common(5))

以上从最后一条推文中产生5个随机单词,每个单词的计数为7 - 这意味着它基本上读取了最后一条推文7次,而不是一次读取7条推文中的每一条。

以下代码旨在查看哪些单词最常组合在一起。它从最后一条推文中产生5个随机分组的单词,计数仅为1,这表示它只读取最后一条推文(一次)而没有其他推文。

with open(fname, 'r', encoding='utf8') as f:
count_all = Counter()
# Create a list with all the terms
terms_stop = [term for term in tokens if term not in stop]
# Import Bigrams to group words together
terms_bigram = bigrams(terms_stop)
for line in f:
    # Update the counter
    count_all.update(terms_bigram)
# Print the first 5 most frequent words
print(count_all.most_common(5))

我的json文件的格式如下:

{"created_at":"Tue Oct 25 11:24:54 +0000 2016","id":4444444444,.....}
{"created_at":..... }
{etc}

非常感谢帮助!首先十分感谢。

更新: 不知道我怎么错过它,但感谢大家的帮助!我忘了在for循环中包含'line'。这是工作代码:

with open(fname, 'r', encoding='utf8') as f:
count_all = Counter()
for line in f:
    tweet = json.loads(line)
    tokens = preprocess(tweet['text'])
    # Create a list with all the terms
    terms_stop = [term for term in tokens if term not in stop]
    # Update the counter
    count_all.update(terms_stop)
# Print the first 5 most frequent words
print(count_all.most_common(5))

我只需将标记化器与字数统计在一起。

2 个答案:

答案 0 :(得分:1)

也许我错过了一些东西,但你从不在for-loop中使用line:

for line in f:
    # Update the counter
    count_all.update(terms_bigram)

所以你只是循环遍历为每一行做同样事情的行。

答案 1 :(得分:0)

尝试此操作阅读文件:

auto get_fun(int arg) -> double (*)(double) // same as: double (*get_fun(int))(double)
{
    switch (arg)
    {
        case 1: return std::fabs;
        case 2: return std::sin;
        default: return std::cos;
    }
}

如果这不起作用,请发布有关文件数据格式的更多信息。

新更新:

with open(fname) as d:
    tweet = json.load(d)

这将为您提供字典列表(json格式)

相关问题