-- coding: utf-8 -- """This script calculates rizzoma topics' stats.""" import…
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
-- coding: utf-8 --
"""This script calculates rizzoma topics' stats.""" import collections import csv import json import logging import os import typing from datetime import datetime
from bs4 import BeautifulSoup # type: ignore
Data = typing.Dict[ str, typing.Union[str, int, typing.DefaultDict[str, typing.List[str]]] ]
root = os.path.dirname(os.path.abspath(file)) backups = os.path.join(root, "data", "backups") analytics = os.path.join(root, "data", "analytics") lookups = os.path.join(root, "parsing-lookup.json")
def create_logger(name: str = "backup.log") -> logging.Logger: """Creates logger.""" _logger = logging.getLogger(name) _logger.setLevel(logging.DEBUG) file_handler = logging.FileHandler(os.path.join(root, name)) file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s [%(levelname)s]: %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) _logger.addHandler(file_handler) _logger.addHandler(stream_handler) return _logger
logger = create_logger("rizzoma-analytics.log")
def read_lookup(lookup: str) -> typing.Dict[str, str]: """Reads json file with mapped CSS selectors.""" with open(lookup, encoding="utf-8") as fp: data = json.load(fp) return data
lookup = read_lookup(lookups)
def parse_datetime(timestamp: str) -> datetime: """Parses timestamp like string into datetime object.""" return datetime.strptime(timestamp, "%Y-%m-%d %I:%M %p")
def parse_html(html_file: str) -> Data: """Parses html file extracting useful data.""" with open(os.path.join(backups, html_file)) as fp: soup = BeautifulSoup(fp, "html.parser") metadata = soup.select_one(lookup["export-reply-info"]) replies = soup.select(lookup["replies"])
codeactivity = collections.defaultdict(list) for reply in replies: user_name = reply.a["href"].split(":")[-1] activity[user_name].append(reply.span["title"]) stats = {k: len(v) for k, v in activity.items()} unique_ts = {parse_datetime(ts) for user in activity.values() for ts in user} return { "title": soup.select_one(lookup["title"]).text, "author_id": metadata.a["href"].split(":")[-1], "author_name": metadata.a["title"], "created_at": datetime.strftime(min(unique_ts), "%Y-%m-%d %I:%M %p"), "url": soup.select_one(lookup["original-url"])["href"], "number_of_messages": sum(stats.values()), "participants": ";".join(activity.keys()), "number_of_participants": len(stats), "latest_message_at": datetime.strftime(max(unique_ts), "%Y-%m-%d %I:%M %p"), "activity_per_user": activity, } - Assistant
This script calculates Rizzoma topics' stats. It defines several functions to:
- Create a logger object for logging messages.
- Read a JSON file containing mapped CSS selectors.
- Parse a given HTML file and extract useful data.
- Write the extracted data to a CSV file.
- Run the pipeline by processing all HTML files in the
backupsdirectory and writing the results to a CSV file.
The script uses the
BeautifulSouplibrary to parse HTML and extract data based on the provided CSS selectors. It also uses thecsvlibrary to write the extracted data to a CSV file.The main function
main()is the entry point of the script. It processes all HTML files in thebackupsdirectory, extracts the required data, and writes it to a CSV file. If there is an error while parsing an HTML file, the script logs the error message and continues processing the remaining files.To run the script, simply execute it in a Python environment with the required libraries installed. The script will create a CSV file named
stats.csvin thedatadirectory containing the extracted data. - User
!Is there a way to aslo scrape the number of chars for each message?This content may violate our content policy. If you believe this to be in error, please submit your feedback — your input will aid our research in this area.
- Assistant
Yes, you can modify the
parse_htmlfunction to extract the number of characters for each message. Here's an updated version of theparse_htmlfunction that includes the character count:python - User
Full code block please?
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.