#python #json #path #pathlib
#python #json #путь #pathlib
Вопрос:
Итак, у меня есть функция, которая очищает данные Instagram и сохраняет количество лайков в словаре.Я думаю, что у меня правильно настроена функция, но когда я пытаюсь запустить оператор печати, я продолжаю получать сообщение об ошибке, что он не может найти файл, который я ищу для запуска через функцию.
Это код, который я использую для монтирования моего Google диска и установки каталога для хранения моих файлов json. Я проверил, что все это правильно на моем диске.
# Mount data location. Do not edit this cell except as indicated.
# Be sure you have a folder in the root of your Google Drive called APRD6342/Data.
# Data files for the course should be uploaded to that folder.
from pathlib import Path
try:
from google.colab import drive
drive.mount('/content/drive')
datadir = Path('drive/My Drive/APRD6342/Data') # you may edit this location ...
except ModuleNotFoundError:
datadir = Path('../../Data') # ... but don't change this!!!
INSTAGRAM_DIR = datadir / 'instagram'
Вот моя функция:
def engagement(filename, follower_count):
"""Return the brand post engagement for the Instagram metadata file,
filename, given follower_count as the number of Instagram followers for
the brand.
Returns a decimal engagement rate rounded to 4 decimal places. Python's
standard `round` function should be used. E.g.:
>>> engagement('instagram/volvocars.json', volvocars_follower_count)
0.0125
"""
with open(datadir / filename) as f:
for line in f: #for each line in the file
line_object = json.loads(line)
likes = line_object["GraphImages"]["edge_media_preview_like"]["count"] #find count
if num in likes > 1:
engagement.append(i) #add count to engagement
comments = filename["GraphImages"]["edge_media_to_comment"]["count"] #find other count
if num in comments > 1:
engagement.append(i) #add count
engage_perc = sum(engagement)/follower_count #sum all counts and divide by the number of followers
return engage_perc
вот инструкция print, которую я пытаюсь запустить, и ошибка:
print('Honda:',
as_percent(engagement(INSTAGRAM_DIR / 'honda.json', honda_follower_count)))
---> 12 with open(datadir / filename) as f:
13 for line in f: #for each line in the file
14 line_object = json.loads(line)
FileNotFoundError: [Errno 2] No such file or directory: 'drive/My Drive/APRD6342/Data/drive/My Drive/APRD6342/Data/instagram/honda.json'
Я запускал этот код монтирования раньше нормально, но по какой-то причине мой каталог сам вложен или что-то в этом роде. Спасибо!
Комментарии:
1. Попробуйте использовать
os.path.abspath()
в соответствии с документами os.path.abspath() возвращает нормализованную абсолютизированную версию пути path, который может показаться причудливым, но это просто означает, что этот метод возвращает путь к пути, переданному в качестве параметра этой функции.
Ответ №1:
когда вы вызываете функцию с
print('Honda:',
as_percent(engagement(INSTAGRAM_DIR / 'honda.json', honda_follower_count)))
вы указываете полный путь, но затем в функции путь добавляется снова
with open(datadir / filename) as f:
Передайте только вложенную instagram
папку и имя файла. Обратите внимание на строку документа — они предоставляют 'instagram/volvocars.json'
, поэтому вам нужно предоставить 'instagram/honda.json'
Ответ №2:
Так что смог найти способ не использовать файл jsonl, а просто json. Путал некоторый синтаксис.
def engagement(filename, follower_count):
"""Return the brand post engagement for the Instagram metadata file,
filename, given follower_count as the number of Instagram followers for
the brand.
Returns a decimal engagement rate rounded to 4 decimal places. Python's
standard `round` function should be used. E.g.:
>>> engagement('instagram/volvocars.json', volvocars_follower_count)
0.0125
"""
engagement = [] #set empty list for like counts
data = filename #store filename to variable
with open(data) as f: #save open file as outfile
parse = json.load(f)
for n in range(0,200):
likes = parse["GraphImages"][n]["edge_media_preview_like"]["count"] #find count
if likes > 1:
engagement.append(likes) #add count to engagement
comments = parse["GraphImages"][n]["edge_media_to_comment"]["count"] #find other count
if comments > 1:
engagement.append(comments) #add count
engage_perc = (sum(engagement)/len(range(0,200)))/follower_count #sum all counts and divide by the number of followers
return round(engage_perc,4)