Advertisement
Python253

extract_quoted_text

Mar 5th, 2024
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: extract_quoted_text.py
  4. # Author: Jeoi Reqi
  5.  
  6. """
  7. This Python script extracts text enclosed in double quotes from a specified input file.
  8. It reads the content of the input file, searches for text surrounded by double quotes using regex,
  9. and writes the extracted text to a specified output file.
  10.  
  11. Usage:
  12. - Place the script in the same directory as the input file.
  13. - Update 'input_filename' and 'output_filename' variables with the appropriate file names.
  14. - Run the script to extract and save the quoted text.
  15.  
  16. Requirements:
  17. - This script requires Python 3.
  18. """
  19.  
  20. def extract_quoted_text(input_file, output_file):
  21.     try:
  22.         with open(input_file, 'r', encoding='utf-8') as input_file:
  23.             content = input_file.read()
  24.  
  25.         # Extract text enclosed in double quotes using regex
  26.         import re
  27.         quoted_text = re.findall(r'"([^"]*)"', content)
  28.  
  29.         # Write the extracted text to the output file
  30.         with open(output_file, 'w', encoding='utf-8') as output_file:
  31.             for text in quoted_text:
  32.                 output_file.write(text + '\n')
  33.  
  34.         print(f'Successfully extracted quoted text from {input_file.name} to {output_file.name}.')
  35.     except Exception as e:
  36.         print(f'An error occurred: {e}')
  37.  
  38. # Example usage
  39. input_filename = 'input.txt'  # Replace 'input.txt' with your input filename
  40. output_filename = 'output.txt'  # Replace 'output.txt' with your output filename
  41. extract_quoted_text(input_filename, output_filename)
  42.  
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement