本文整理汇总了Python中parsing.parser.Parser类的典型用法代码示例。如果您正苦于以下问题:Python Parser类的具体用法?Python Parser怎么用?Python Parser使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Parser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _build_tracking_effects
def _build_tracking_effects(events: list, screen_data: dict, ship: ShipStats):
"""Determine tracking penalty for each primary weapon event"""
active_ids = Parser.get_player_id_list(events)
distance = screen_data["distance"]
primary = "PrimaryWeapon"
for i, event in enumerate(events):
if "custom" in event and event["custom"] is True:
continue
if "Primary Weapon Swap" in event["ability"] and event["self"] is True:
primary = "PrimaryWeapon2" if primary == "PrimaryWeapon" else "PrimaryWeapon"
continue
ctg = Parser.get_event_category(event, active_ids)
if ctg != "dmgd_pri":
continue
key = min(distance.keys(), key=lambda k: abs((k - event["time"]).total_seconds()))
if abs((key - event["time"]).total_seconds()) > 0.5:
continue
if primary not in ship:
continue
tracking = ship[primary]["trackingAccuracyLoss"] * (distance[key] / 10) * 100
del events[i]
event["effects"] = (
("", "Tracking", "Penalty", "-{:.0f}%".format(tracking), "", "spvp_improvedfiringarctrackingbonus"),
)
events.append(event)
return events
示例2: parse_spawn
def parse_spawn(self, elements):
"""
Either starts the parsing of ALL spawns found in the specified
match or just one of them and displays the results in the other
frames accordingly.
"""
self.clear_data_widgets()
self.main_window.middle_frame.statistics_numbers_var.set("")
self.main_window.ship_frame.ship_label_var.set("No match or spawn selected yet.")
file_name, match_index, spawn_index = elements[0], int(elements[1]), int(elements[2])
lines = Parser.read_file(file_name)
player_list = Parser.get_player_id_list(lines)
player_name = Parser.get_player_name(lines)
file_cube, match_timings, spawn_timings = Parser.split_combatlog(lines, player_list)
match = file_cube[match_index]
spawn = match[spawn_index]
results = list(spawnstats.spawn_statistics(
file_name, spawn, spawn_timings[match_index][spawn_index]))
results[1] = Parser.parse_player_reaction_time(spawn, player_name)
orig = len(results[1])
results[1] = ScreenParser.build_spawn_events(
file_name, match_timings[::2][match_index], spawn_timings[match_index][spawn_index], spawn, player_name)
print("[FileFrame] ScreenParser built {} events. Total: {}".format(len(results[1]) - orig, len(results[1])))
self.update_widgets_spawn(*results)
arguments = (file_name, match_timings[::2][match_index], spawn_timings[match_index][spawn_index])
string = FileHandler.get_features_string(*arguments)
self.main_window.middle_frame.screen_label_var.set(string)
self.main_window.middle_frame.update_timeline(
file_name, match_index, spawn_index, match_timings, spawn_timings, file_cube)
示例3: update_files
def update_files(self):
"""Update the Calendar with the new files"""
self.clear_data_widgets()
self._dates.clear()
folder = variables.settings["parsing"]["path"]
if not os.path.exists(folder):
messagebox.showerror("Error",
"The specified CombatLogs folder does not exist. Please "
"choose a different folder.")
folder = filedialog.askdirectory()
variables.settings.write_settings({"parsing": {"path": folder}})
return self.update_files()
files = [f for f in os.listdir(folder) if Parser.get_gsf_in_file(f)]
self.create_splash(len(files))
match_count: Dict[datetime: int] = DateKeyDict()
for file in files:
date = Parser.parse_filename(file)
if date is None: # Failed to parse
continue
if date not in match_count:
match_count[date] = 0
match_count[date] += Parser.count_matches(file)
if date not in self._dates:
self._dates[date] = list()
self._dates[date].append(file)
self._splash.increment()
self._calendar.update_heatmap(match_count)
self.destroy_splash()
示例4: test_single_indent_spaces
def test_single_indent_spaces(self):
parser = Parser()
parsed = parser.parse_line("\t FEATURE TYPE: ## ADHOC")
self.assertIsNotNone(parsed)
indent, node = parsed
self.assertEqual(1, indent)
示例5: test_no_indent
def test_no_indent(self):
parser = Parser()
parsed = parser.parse_line("FEATURE TYPE: ## ADHOC")
self.assertIsNotNone(parsed)
indent, node = parsed
self.assertEqual(0, indent)
示例6: parse_ship_descriptor
def parse_ship_descriptor(ship: Ship, line: dict, lines: list, event: tuple):
"""
Parse an event_descriptor of the SHIP type. Supports ability,
component and crew type operations.
:param ship: Ship instance for the spawn described by lines
:param line: Trigger line dictionary
:param lines: List of lines in this spawn
:param event: Event descriptor tuple (PatternParser docstring)
:return: The result of results this SHIP event descriptor
"""
if event[0] != Patterns.SHIP:
raise InvalidDescriptor(event)
event_type, args = event[1], event[2:] # "ability", "component", "crew"
# Parse Component selected
if event_type == "component":
# Component must be selected on the Ship for this spawn
component, = args
return PatternParser.get_component_in_ship(lines, ship, component)
# Parse Crew selected
elif event_type == "crew":
crew, = args
return PatternParser.get_crew_in_ship(ship, crew)
# Parse Ability Available
elif event_type == "ability":
return PatternParser.parse_ability_availability(line, lines, event, ship)
# Parse ship type selected
elif event_type == "type":
# TODO: Optimize usage
player = Parser.get_player_id_list(lines)
abs_dict = Parser.get_abilities_dict(lines, player)
ship_name = ship.name if ship is None else Parser.get_ship_for_dict(abs_dict)
ship_type, = args
return get_ship_category(ship_name) == ship_type
raise InvalidDescriptor(event)
示例7: get_component_in_ship
def get_component_in_ship(lines: list, ship: Ship, component: (str, Component)):
"""Return whether a component is found within a Ship instance"""
if isinstance(component, Component):
name, category = component.name, component.category
else: # str
name = component
category = PatternParser.get_component_category(component)
player = Parser.get_player_id_list(lines)
abilities = Parser.get_abilities_dict(lines, player)
if name in abilities:
return True
if ship is None:
return False # Ship option not available at results time
if category not in ship:
return False # Configured improperly at results time
categories = (category,)
if "Weapon" in category: # Extend to double primaries/secondaries
categories += (category[0] + "2",)
# Loop over categories
result = False
for category in categories:
if category not in ship: # Double primaries/secondaries
continue
component = ship[category]
if not isinstance(component, Component): # Improper config
print("[PatternParser] Improperly configured Ship instance:", ship, component)
continue
if component.name == name:
result = True
break
continue
return result
示例8: get_ability_markers
def get_ability_markers(spawn_list, ship_stats):
"""
Parse a spawn list of lines and take the Engine, Shield, Systems
and CoPilot ability activations and create markers for them to
be put in the TimeLine.
"""
# TODO: Use ship_statistics to create availability markers
categories = ["engines", "shields", "copilot", "systems"]
player_id_list = Parser.get_player_id_list(spawn_list)
results = {key: [] for key in categories}
# Activation markers
for line in spawn_list:
if not isinstance(line, dict):
line = Parser.line_to_dictionary(line)
ability = line["ability"]
if (line["source"] != line["target"] or line["source"] not in player_id_list or
"AbilityActivate" not in line["effect"]):
continue
if ability in abilities.copilots:
category = "copilot"
elif ability in abilities.shields:
category = "shields"
elif ability in abilities.systems:
category = "systems"
elif ability in abilities.engines:
category = "engines"
else:
continue
start = FileHandler.datetime_to_float(line["time"])
args = ("abilities", start, start + 1/60)
kwargs = {"background": FileHandler.colors[category]}
results[category].append((args, kwargs))
return results
示例9: test_multiple_indent_mixed
def test_multiple_indent_mixed(self):
parser = Parser()
parsed = parser.parse_line("\t \t->FEATURE TYPE: ## ADHOC")
self.assertIsNotNone(parsed)
indent, node = parsed
self.assertEqual(2, indent)
示例10: main
def main():
"""
Main entry point into the program. Parse the command line arguments of the
form [lexicon_file grammar_file source_file].
Calls lexer to obtain a sequence L of annotated lexemes from the source file
and lexicon file. Calls parser to obtain an abstract syntax tree from L and
grammar file and print it.
"""
# read arguments
(options, args) = parse_arguments()
(lexicon_file, grammar_file, input_file) = args
# create lexer instance
lexer_instance = Lexer(lexicon_file, options.use_builtin_lexemes)
# obtain lexing sequence from the input file
lexing_sequence = lexer_instance.get_lexing_sequence_from_file(input_file)
# create parser instance
parser_instance = Parser(grammar_file, lexer_instance.lexicon_dict.keys())
# obtain abstract syntax tree from the lexing sequence
print(parser_instance.get_ast(lexing_sequence, options.ignore_spaces))
示例11: test_adhoc
def test_adhoc(self):
parser = Parser()
parsed = parser.parse_line("FEATURE TYPE: ## ADHOC")
self.assertIsNotNone(parsed)
indent, node = parsed
self.assertEqual(["adhoc"], node.features())
self.assertEqual('feature', node.line_type())
self.assertEqual('FEATURE TYPE: ## ADHOC', node.line())
示例12: get_treeview_values
def get_treeview_values(line_dict, player_name, start_time, active_ids):
"""Return the Treeview values for a certain line_dict"""
values = (
TimeView.format_time_diff(line_dict["time"], start_time),
player_name if Parser.compare_ids(line_dict["source"], active_ids) else line_dict["source"],
player_name if Parser.compare_ids(line_dict["target"], active_ids) else line_dict["target"],
line_dict["ability"],
line_dict["amount"]
)
return values
示例13: update_files
def update_files(self, silent=False):
"""
Function that checks files found in the in the settings
specified folder for GSF matches and if those are found in a
file, it gets added to the listbox. Provides error handling.
"""
self.file_tree.delete(*self.file_tree.get_children())
self.clear_data_widgets()
self.main_window.ship_frame.ship_label_var.set("")
try:
old_cwd = os.getcwd()
os.chdir(variables.settings["parsing"]["path"])
os.chdir(old_cwd)
except OSError:
tkinter.messagebox.showerror("Error",
"The CombatLogs folder found in the settings file is not valid. Please "
"choose another folder.")
folder = tkinter.filedialog.askdirectory(title="CombatLogs folder")
variables.settings.write_settings({'parsing': {'path': folder}})
variables.settings.read_settings()
combatlogs_folder = variables.settings["parsing"]["path"]
file_list = os.listdir(combatlogs_folder)
if not silent:
splash_screen = SplashScreen(self.main_window, len(file_list), title="Loading files")
else:
splash_screen = None
if len(file_list) > 100:
tkinter.messagebox.showinfo("Suggestion", "Your CombatLogs folder contains a lot of CombatLogs, {0} to be "
"precise. How about moving them to a nice archive folder? This "
"will speed up some processes "
"significantly.".format(len(file_list)))
self.file_tree.insert("", tk.END, iid="all", text="All CombatLogs")
file_list = list(reversed(sorted(file_list)) if not self.ascending else sorted(file_list))
if self.main_window.splash is not None and self.main_window.splash.winfo_exists():
self.main_window.splash.update_max(len(file_list))
for number, file in enumerate(file_list):
if not Parser.get_gsf_in_file(file):
continue
file_string = Parser.parse_filename(file)
if file_string is None:
continue
self.file_string_dict[file_string] = file
number += 1
if splash_screen is not None:
splash_screen.increment()
splash_screen.update()
self.insert_file(file_string)
if self.main_window.splash is not None and self.main_window.splash.winfo_exists():
self.main_window.splash.increment()
if splash_screen is not None:
splash_screen.destroy()
return
示例14: test_get_effects_ability_eligible
def test_get_effects_ability_eligible(self):
with open(self.FILE) as fi:
lindex = fi.readlines()
index = lindex.index(self.EFFECT)
no_effect = lindex.index(self.LINE)
lines = Parser.read_file(self.FILE)
player = Parser.get_player_id_list(lines)
line = Parser.line_to_dictionary(lines[index], player)
effect = Parser.get_effects_ability(line, lines, "2963000049645")
self.assertIsInstance(effect, dict)
self.assertTrue(len(effect) > 0)
# Tests get_effects_eligible
self.assertFalse(Parser.get_effects_ability(lines[no_effect], lines, "2963000048240"))
示例15: test_parse_file_stats
def test_parse_file_stats(self):
lines = [
"true", "Using complex purge",
"bloop", "bleep",
"FEATURE TYPE: ## ADHOC",
]
parser = Parser()
stats = parser.parse_file(lines)
self.assertEqual(5, stats['nb_read'])
self.assertEqual(1, stats['nb_parsed'])
self.assertEqual(2, stats['nb_skipped'])