isPrime/convert_primelist.py

29 lines
810 B
Python

import json
def convert_primes_to_json(file_path):
# Step 1: Read the file content
with open(file_path, 'r') as file:
lines = file.readlines()
primes = []
for line in lines:
# Step 2: Extract prime numbers
# Split each line into words and filter out non-numeric entries
numbers = [int(num) for num in line.split() if num.isdigit()]
primes.extend(numbers)
# Step 3: Convert the list of primes to a JSON array
primes_json = json.dumps(primes, indent=4)
return primes_json
# Example usage:
file_path = 'primes1.txt'
primes_json = convert_primes_to_json(file_path)
print(primes_json)
# If you want to save the JSON array to a file:
output_path = 'primes1.json'
with open(output_path, 'w') as output_file:
output_file.write(primes_json)