Python, как получить количество уникальных идентификаторов на файл и сохранить имя файла и уникальные идентификаторы для каждого файла в CSV-файле? - PullRequest
0 голосов
/ 24 сентября 2018

Я работаю над проектом по подсчету уникальных комментаторов в чате и сохранению имени файла и количества комментаторов этого чата в CSV для каждого файла.Тем не менее, код, который у меня сейчас есть, открывает все документы и считает все комментарии в нескольких файлах.Таким образом, вместо того, чтобы получать отдельные уникальные комментарии для каждого файла, он считает все комментарии для нескольких файлов.Во всех файлах имеется 10 уникальных комментариев, однако мне нужно иметь возможность видеть количество уникальных комментариев для каждого файла и сохранять эти данные в файле csv (см. «Требуемый вывод» для изображения файла csv).Я чувствую, что я очень близко, но я застрял.Может кто-нибудь помочь с этой проблемой или предложить другие методы в этом?

import os, sys, json
from collections import Counter
import csv
filename=""
filepath = ""
jsondata = ""
dictjson = ""
commenterid = []
FName = []
UList = []
TextFiles = []
UCommenter = 0


def get_FilePathList():
    for root, dirs, files in os.walk("/Users/ammcc/Desktop/"):
        for file in files:
            ##Find File with specific ending
            if file.endswith("chatinfo.txt"):
                path = "/Users/ammcc/Desktop/"
                ##Get the File Path of the file
                filepath = os.path.join(path,file)
                ##Get the Filename of the file ending in chatinfo.txt
                head, filename = os.path.split(filepath)
                ##Append all Filepaths of files ending in chatinfo.txt to TextFiles array/list
                TextFiles.append(filepath)
                ##Append all Filenames of files ending in chatinfo.txt to FName array/list
                FName.append(filename)

def open_FilePath():
     for x in TextFiles:
            ##Open each filepath in TextFiles one by one
            open_file = open(x)
            ##Read that file line by line
            for line in open_file:
                    ##Parse the Json of the file into jsondata
                    jsondata = json.loads(line)
                    ##Line not needed but, Parse the Json of the file into dictjson as Dictionary
                    dictjson = json.dumps(jsondata)

                    ## if the field commenter is found in jsondata
                    if "commenter" in jsondata:
                                    ##Then, append the field  ["commenter"]["_id"] **(nested value in the json)** into list commenterid
                                    commenterid.append(jsondata["commenter"]["_id"])
                                    ##Get and count the unique ids for the commenter
                                    Ucommenter = (len(set(commenterid)))
                                    ##Appended that unique count in UList
                                    UList.append(Ucommenter)


                                    ## create or append to the Commenter.csv file
                                    with open('Commenter.csv', 'a') as csvfile:
                                            filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
                                            ##Write the individual filename and the unique commenters for that file
                                            filewriter.writerow([filename, Ucommenter])
            commenterid.clear()

                                            ##Issue: Not counting the commenters for each file and storing the filename and its specific number of commneters in csv.
                                            ##the cvs is being created but the rows in the csv is not generating correctly.

##Call the functions                                                     
get_FilePathList()
open_FilePath()

Токовый выход в CSV-файле

enter image description here

Требуемый выход для CSV-файла

enter image description here

Вывод после предложения

enter image description here

Вывод и код после решения Неманьи Радойковича:

** Правильный формат вывода, но все равно не считая уникальных комментаторов для файла.

enter image description here

import json, os
import pandas as pd
import numpy as np
from collections import Counter
TextFiles = []
FName = []
csv_rows = []
commenterid = []
unique_id = []
NC = []
for root, dirs, files in os.walk("/Users/ammcc/Desktop/"):
 for file in files:
     if file.endswith("chatinfo.txt"):
         path = "/Users/ammcc/Desktop/"
         filepath = os.path.join(path,file)
         head, filename = os.path.split(filepath)
         TextFiles.append(filepath)
         FName.append(filename)

         n_commenters = 0
         with open(filepath) as open_file:
             for line in open_file:
                 jsondata = json.loads(line)
                 if "commenter" in jsondata:
                     commenterid.append(jsondata["commenter"]["_id"])

                     list_set = set(commenterid)
                     unique_list = (list(list_set))

                 for x in list_set:
                     n_commenters += 1

                     commenterid.clear()
             csv_rows.append([filename, n_commenters])
df = pd.DataFrame(csv_rows, columns=['FileName', 'Unique_Commenters'])
df.to_csv('CommeterID.csv', index=False)

1 Ответ

0 голосов
/ 24 сентября 2018

Попробуйте это:

import json
import os
import pandas as pd

TextFiles = []
FName = []
csv_rows = []

for root, dirs, files in os.walk("/Users/ammcc/Desktop/"):

    for file in files:
        ##Find File with specific ending
        if file.endswith("chatinfo.txt"):

            path = "/Users/ammcc/Desktop/"
            ##Get the File Path of the file
            filepath = os.path.join(path,file)
            ##Get the Filename of the file ending in chatinfo.txt
            head, filename = os.path.split(filepath)
            ##Append all Filepaths of files ending in chatinfo.txt to TextFiles array/list
            TextFiles.append(filepath)
            ##Append all Filenames of files ending in chatinfo.txt to FName array/list
            FName.append(filename)

            n_commenters = 0

            with open(filepath) as open_file:
                ##Read that file line by line


                for line in open_file:
                        ##Parse the Json of the file into jsondata
                        jsondata = json.loads(line)

                        ## if the field commenter is found in jsondata
                        if "commenter" in jsondata:

                            n_commenters += 1

            csv_rows.append([filename, n_commenters])


df = pd.DataFrame(csv_rows, columns=['filename', 'n_commenters'])

df.to_csv('some_filename.csv', index=False)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...