上传文件至 /

This commit is contained in:
Jack_Liu 2024-06-16 15:05:13 +00:00
parent ee7feb07d1
commit cd2511327f
5 changed files with 260 additions and 21 deletions

35
.coveragerc Normal file
View File

@ -0,0 +1,35 @@
# .coveragerc to control coverage.py
[run]
branch = True
omit =
__main__.py
[report]
# Regexes for lines to exclude from consideration
exclude_lines =
# Have to re-enable the standard pragma
pragma: no cover
# Don't complain about missing debug-only code:
def __repr__
# Don't complain if tests don't hit defensive assertion code:
raise AssertionError
raise NotImplementedError
# Don't complain if non-runnable code isn't run:
if 0:
if __name__ == .__main__.:
# Don't complain about abstract methods, they aren't run:
@(abc\.)?abstractmethod
# Don't complain aboud typing hint
class (\w+)\(Protocol\):
@(typing\.)?overload
# Don't complain about deprecated code
@(typing(_extensions)?\.)?deprecated(.*)
ignore_errors = True

162
.gitignore vendored Normal file
View File

@ -0,0 +1,162 @@
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 SoftwareLab
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

24
Makefile Normal file
View File

@ -0,0 +1,24 @@
.PHONY: run refresh test lint coverage clean
MODULE := lab1.py
all: clean test lint
refresh: clean test lint
run:
python ${MODULE}
lint:
flake8 ${MODULE} tests/ --exclude __init__.py --count --max-line-length=127 --extend-ignore=W293,E402
test:
pytest
coverage:
coverage run --source $(basename ${MODULE}) --parallel-mode -m pytest
coverage combine
coverage html -i
clean:
rm -rf build
rm -rf dist

47
lab1.py
View File

@ -7,7 +7,7 @@ from random import choice
from tkinter import ttk from tkinter import ttk
from tkinter.filedialog import askopenfile from tkinter.filedialog import askopenfile
from tkinter.messagebox import showerror, showinfo from tkinter.messagebox import showerror, showinfo
from typing import Dict, Generator, List, Optional, cast from typing import IO, Dict, Generator, List, Optional, cast
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import networkx as nx import networkx as nx
@ -165,7 +165,7 @@ class SideFrame(tk.Frame):
class MainWindow(ttk.Frame): class MainWindow(ttk.Frame):
def setup(self) -> None: def setup(self) -> None:
self.load_button = ttk.Button(self, text="Load", command=self.load_file) self.load_button = ttk.Button(self, text="Load", command=self._load_callback)
self.load_button.pack(side=tk.LEFT, padx=(250, 250), pady=(250, 250)) self.load_button.pack(side=tk.LEFT, padx=(250, 250), pady=(250, 250))
self.graph = nx.DiGraph() self.graph = nx.DiGraph()
self.graph_layout = {} self.graph_layout = {}
@ -173,9 +173,29 @@ class MainWindow(ttk.Frame):
self.side_menu.setup() self.side_menu.setup()
self.side_menu.pack(side=tk.RIGHT, fill=tk.Y) self.side_menu.pack(side=tk.RIGHT, fill=tk.Y)
def load_file(self, file: IO[bytes], *, encoding: str = "utf-8") -> None:
"""load text from file
:param file: file to load
:type file: IO
"""
text: str = file.read().decode(encoding=encoding)
last = None
for t in re.split(r"[^A-Za-z]+", text.lower()):
if not t:
continue
self.graph.add_node(t)
if last is not None:
if (last, t) not in self.graph.edges:
self.graph.add_edge(last, t, weight=1)
else:
self.graph.edges[last, t]["weight"] += 1
last = t
def show_directed_graph(self) -> None: def show_directed_graph(self) -> None:
"""show directed graph in matplotlib"""
f = plt.figure(figsize=(7, 7)) f = plt.figure(figsize=(7, 7))
pos = nx.spring_layout(self.graph, iterations=256) pos = nx.spring_layout(self.graph)
nx.draw(self.graph, with_labels=True, pos=pos) nx.draw(self.graph, with_labels=True, pos=pos)
labels = nx.get_edge_attributes(self.graph, 'weight') labels = nx.get_edge_attributes(self.graph, 'weight')
nx.draw_networkx_edge_labels(self.graph, pos, edge_labels=labels) nx.draw_networkx_edge_labels(self.graph, pos, edge_labels=labels)
@ -202,8 +222,8 @@ class MainWindow(ttk.Frame):
paths = all_simple_paths_graph(self.graph, word1, word2) paths = all_simple_paths_graph(self.graph, word1, word2)
words = set() words = set()
for path in paths: for path in paths:
if len(path) == 3: if len(path) != 3:
print(path) continue
words.update(path[1:-1]) words.update(path[1:-1])
return " ".join(words) return " ".join(words)
@ -269,7 +289,7 @@ class MainWindow(ttk.Frame):
while prev := previous_nodes[current_node]: while prev := previous_nodes[current_node]:
path.insert(0, current_node) path.insert(0, current_node)
current_node = prev current_node = prev
if path: # if path:
path.insert(0, current_node) path.insert(0, current_node)
if isinf(distances[word2]): if isinf(distances[word2]):
@ -308,7 +328,7 @@ class MainWindow(ttk.Frame):
nx.draw_networkx_edge_labels(self.graph, pos, edge_labels=nx.get_edge_attributes(self.graph, 'weight')) nx.draw_networkx_edge_labels(self.graph, pos, edge_labels=nx.get_edge_attributes(self.graph, 'weight'))
self.graph_canvas.draw() self.graph_canvas.draw()
def load_file(self) -> None: def _load_callback(self) -> None:
file = askopenfile( file = askopenfile(
"rb", "rb",
defaultextension=".txt", defaultextension=".txt",
@ -319,18 +339,7 @@ class MainWindow(ttk.Frame):
if file is None: if file is None:
return return
with file: with file:
text: str = file.read().decode() self.load_file(file)
last = None
for t in re.split(r"[^A-Za-z]+", text.lower()):
if not t:
continue
self.graph.add_node(t)
if last is not None:
if (last, t) not in self.graph.edges:
self.graph.add_edge(last, t, weight=1)
else:
self.graph.edges[last, t]["weight"] += 1
last = t
self.side_menu.activate() self.side_menu.activate()
self.show_directed_graph() self.show_directed_graph()