Ejercicios 9b y 9c
This commit is contained in:
parent
ffd1ce42ba
commit
fa9584b269
|
@ -0,0 +1,21 @@
|
||||||
|
"""
|
||||||
|
Project: Mad Libs
|
||||||
|
Page 230
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
keywords = ["ADJECTIVE", "NOUN", "ADVERB", "VERB"]
|
||||||
|
infile = Path(sys.argv[1])
|
||||||
|
outfile = infile.parent / f"{infile.stem}.res{infile.suffix}"
|
||||||
|
text = infile.read_text()
|
||||||
|
matches = re.finditer(r'(' + r'|'.join(keywords) + r')', text)
|
||||||
|
|
||||||
|
for match in matches:
|
||||||
|
name = match.group()
|
||||||
|
res = input(f"Enter {name.lower()}:\n")
|
||||||
|
text = text.replace(name, res, 1)
|
||||||
|
print(text)
|
||||||
|
outfile.write_text(text)
|
|
@ -0,0 +1,25 @@
|
||||||
|
"""
|
||||||
|
Project: Regex Search
|
||||||
|
Page 230
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
directory = Path(sys.argv[1])
|
||||||
|
keys = "|".join(sys.argv[2:])
|
||||||
|
regex = re.compile(f"({keys})")
|
||||||
|
result = []
|
||||||
|
|
||||||
|
for path in directory.glob("**/*.txt"):
|
||||||
|
text = open(path, "r").readlines()
|
||||||
|
show_header = True
|
||||||
|
for i, line in enumerate(text):
|
||||||
|
if re.match(regex, line):
|
||||||
|
if show_header:
|
||||||
|
result.append(f"\n{path}")
|
||||||
|
show_header = False
|
||||||
|
result.append(f"{i + 1}\t{line.strip()}")
|
||||||
|
|
||||||
|
print("\n".join(result).strip())
|
|
@ -0,0 +1,2 @@
|
||||||
|
The red panda walked to the duck and then sleep. A nearby sheep was
|
||||||
|
unaffected by these events.
|
|
@ -0,0 +1,2 @@
|
||||||
|
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
|
||||||
|
unaffected by these events.
|
|
@ -0,0 +1,3 @@
|
||||||
|
Write a program that opens all .txt files in a folder and searches for any
|
||||||
|
line that matches a user-supplied regular expression. The results should
|
||||||
|
be printed to the screen.
|
|
@ -0,0 +1,11 @@
|
||||||
|
1. What is a relative path relative to?
|
||||||
|
2. What does an absolute path start with?
|
||||||
|
3. What does Path('C:/Users') / 'Al' evaluate to on Windows?
|
||||||
|
4. What does 'C:/Users' / 'Al' evaluate to on Windows?
|
||||||
|
5. What do the os.getcwd() and os.chdir() functions do?
|
||||||
|
6. What are the . and .. folders?
|
||||||
|
7. In C:\bacon\eggs\spam.txt, which part is the dir name, and which part is the base name?
|
||||||
|
8. What are the three “mode” arguments that can be passed to the open() function?
|
||||||
|
9. What happens if an existing file is opened in write mode?
|
||||||
|
10. What is the difference between the read() and readlines() methods?
|
||||||
|
11. What data structure does a shelf value resemble?
|
Loading…
Reference in New Issue