Распознавание и ll(1) тема

This commit is contained in:
2025-05-06 15:40:22 +03:00
parent c186941dce
commit 529da8d98e
6 changed files with 876 additions and 0 deletions

61
lab3/programm/main.py Normal file
View File

@@ -0,0 +1,61 @@
import json
from grammar import Grammar
with open("grammar.txt", "r", encoding="utf-8") as file:
text = file.read()
# text = """
# S -> A b B | d
# A -> C A b | B
# B -> c S d | epsilon
# C -> a | e d
# """
# text = """
# S -> F | ( S + F )
# F -> 1
# """
grammar = Grammar(text)
print("FIRST sets:", grammar.first_sets)
print("FOLLOW sets:", grammar.follow_sets)
with open("grammar_rules.txt", "w", encoding="utf-8") as output_file:
output_file.write(grammar.format_rules())
print("Правила грамматики с номерами сохранены в grammar_rules.txt")
with open("grammar_lookup_table.txt", "w", encoding="utf-8") as output_file:
output_file.write(grammar.format_lookup_table())
print("Таблица синтаксического анализа сохранена в grammar_lookup_table.txt")
input_string = "ich las gestern ein alt Buch"
input_string = "der alt Mann las ein Buch"
input_string = "gestern las der alt Mann ein Buch"
print(f"Analyzing input '{input_string}':")
parse_result = grammar.analyze(input_string)
print(f"Applied rules: {parse_result}")
rule_details = {num: rule for rule, num in grammar.rule_numbers.items()}
with open("analysis_result.txt", "w", encoding="utf-8") as f:
f.write(f"Input: {input_string}\n")
f.write("Applied rules: ")
f.write(str(parse_result))
f.write("\n\n")
f.write("Derivation steps:\n")
current = grammar.start_symbol
f.write(f"{current}\n")
for rule_num in parse_result:
non_terminal, replacement = rule_details[rule_num]
words = current.split()
for i, word in enumerate(words):
if word == non_terminal:
words[i : i + 1] = replacement
break
current = " ".join(words)
f.write(f"{current}\n")
print("Результат анализа сохранен в analysis_result.txt")