【问题标题】:JSON File: Separate Word Count for Different Objects with PythonJSON 文件:使用 Python 对不同对象进行单独的字数统计
【发布时间】:2020-05-04 10:38:13
【问题描述】:

对于当前的一个研究项目,我计划计算 JSON 文件中不同对象的唯一词。理想情况下,输出文件应为"Text Main""Text Pro""Text Con" 中的文本显示单独的字数统计摘要(计算唯一单词的出现)。是否有任何巧妙的调整来实现这一点?

目前,我收到以下错误消息:

File "index.py", line 10, in <module>
text = data["Text_Main"]
TypeError: list indices must be integers or slices, not str

JSON 文件具有以下结构:

[
{"Stock Symbol":"A",
"Date":"05/11/2017",
"Text Main":"Text sample 1",
"Text Pro":"Text sample 2",
"Text Con":"Text sample 3"}
]

而对应的代码如下:

# Import relevant libraries
import string
import json
import csv
import textblob

# Open JSON file and slice by object
file = open("Glassdoor_A.json", "r")
data = json.load(file)
text = data["Text_Main"]

# Create an empty dictionary
d = dict()

# Loop through each line of the file
for line in text:
    # Remove the leading spaces and newline character
    line = line.strip()

    # Convert the characters in line to
    # lowercase to avoid case mismatch
    line = line.lower()

    # Remove the punctuation marks from the line
    line = line.translate(line.maketrans("", "", string.punctuation))

    # Split the line into words
    words = line.split(" ")

    # Iterate over each word in line
    for word in words:
        # Check if the word is already in dictionary
        if word in d:
            # Increment count of word by 1
            d[word] = d[word] + 1
        else:
            # Add the word to dictionary with count 1
            d[word] = 1

# Print the contents of dictionary
for key in list(d.keys()):
    print(key, ":", d[key])

# Save results as CSV
with open('Glassdoor_A.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["Word", "Occurences", "Percentage"])
    writer.writerows([key, d[key])

【问题讨论】:

    标签: python json text nlp


    【解决方案1】:

    首先,密钥应该是"Text Main",其次您需要访问list 中的第一个dict。所以只需像这样提取text 变量:

    text = data[0]["Text Main"]
    

    这应该可以修复错误消息。

    【讨论】:

    • 谢谢,这确实修复了错误消息。作为输出,我现在收到 A 列中的单个字母和 B 列中的数字。需要更改什么来检查单词而不是单个字母?
    • 补充:所有计算的单个字母都是指文件的第一行,而其余数据不包含在分析/输出中。如前所述,如果不包含“Text_Main”规范,则代码可以使用完整的单词。
    • 你需要在stackoverflow上提出一个新问题。这应该是您的软件开发的模式。编写一小段代码,遇到问题,找到修复并修复它。写下一小段代码等等。你上面的问题结合了太多的活动部分,每个部分都有问题,但每个问题又隐藏了下一个问题。
    • 明白了。那么让我总结一个新问题中的基本部分。
    【解决方案2】:

    您的 JSON 文件在列表中有一个对象。为了访问您想要的内容,首先您必须通过data[0] 访问该对象。然后您可以访问字符串字段。我会将代码更改为:

    # Open JSON file and slice by object
    file = open("Glassdoor_A.json", "r")
    data = json.load(file)
    json_obj = data[0]
    text = json_obj["Text_Main"]
    

    或者您可以使用 text = data[0]["Text_Main"] 在一行中访问该字段,如 quamrana 所述。

    【讨论】:

    • 谢谢,这很有帮助。但是,我现在收到单个字母作为输出。这可能是什么原因 - 没有 "Text_Main" 对象规范 - 代码计算完整的单词?
    • 补充:所有计算的单个字母都是指文件的第一行,而其余数据不包含在分析/输出中。如前所述,如果不包含“Text_Main”规范,则代码可以使用完整的单词。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多