理解列表和新文件
Comprehension List and new File
Example of two text files. The left image is before, the right one is after
我需要交换一个文件中的日期,然后使用理解列表将其放入一个新文件中。我该怎么做?这是我的:
list1 = [x.replace("\n","").replace("/"," ").split(" ") for x in open("dobA.txt")]
list2 = [(i[len(i)-2],i[len(i)-3]) for i in list1]
with open("dobB.txt", "w") as newfile:
newfile.write()
最上面一行代码将日期变成了它们自己的字符串,例如“10”。
第二行代码交换了我需要的数字但只打印出来:
[('11', '10'), ('8', '9'), ('9', '7')]
最后两个刚刚写了一个新文件
我如何交换这两个数字并将它们放在一个新文件中?谢谢。
首先,执行此操作:
i[-2]
而不是
i[len(i)-2]
有几个选项可以解决这个问题:
可读但不理解:
with open("old_file.txt") as old_file, open("new_file.txt", "w") as new_file:
for line in old_file:
name, surname, date = line.split()
day, month, year = date.split("/")
print(f"{name} {surname} {month}/{day}/{year}", file=new_file)
正则表达式替换:
import re
from pathlib import Path
text = Path("old_file.txt").read_text()
replaced = re.sub(r"(\d+)/(\d+)/(\d+)", r"//", text)
Path("new_file.txt").write_text(replaced)
如果你真的需要理解:
with open("old_file.txt") as old_file, open("new_file.txt", "w") as new_file:
new_lines = [
f"{text} {date.split('/')[1]}/{date.split('/')[0]}/{date.split('/')[2]}"
for text, date in [line.rsplit(maxsplit=1) for line in old_file]
]
print("\n".join(new_lines), file=new_file)
我想看看这是否可以一次性完成。它可能违背“可读性”。
翻转月份和日期的最简单方法是利用日期时间对象上的 string formatting methods。
有关格式选项,请参阅 Python strftime reference。
from pathlib import Path
import tempfile
from datetime import datetime
import operator as op
# Create temporary files for reading and writing.
_, filename = tempfile.mkstemp()
file_A = Path(filename)
_, filename = tempfile.mkstemp()
file_B = Path(filename)
contents_A = """Adam Brown 10/11/1999
Lauren Marie Smith 9/8/2001
Vincent Guth II 7/9/1980"""
file_A.write_text(contents_A)
# This version requires Python 3.8.
# It uses the newly introduced assignment expression ":=".
# datetime objects have string formatting methods.
file_B.write_text(
"\n".join(# re-join the lines
[
" ".join(# re-join the words
(
# Store the split line into words. Then slice all but last.
" ".join((words := line.split())[:-1]),
# Convert the last word to desired date format.
datetime.strptime(words[-1], "%m/%d/%Y",).strftime("%-d/%-m/%Y",),
)
)
for line in fileA.read_text().splitlines()
]
)
)
print(file_B.read_text())
输出:
Adam Brown 11/10/1999
Lauren Marie Smith 8/9/2001
Vincent Guth II 9/7/1980
如果没有“:=”运算符,问题就多了一点。这意味着必须在理解中调用 line.split()
两次。
file_B.write_text("\n".join([
" ".join(
op.add(
line.split()[:-1],
[
datetime.strptime(
line.split()[-1], "%m/%d/%Y",
).strftime("%-d/%-m/%Y",),
],
)
)
for line in fileA.read_text().splitlines()
]))
print(file_B.read_text())
输出:
Adam Brown 11/10/1999
Lauren Marie Smith 8/9/2001
Vincent Guth II 9/7/1980
Example of two text files. The left image is before, the right one is after
我需要交换一个文件中的日期,然后使用理解列表将其放入一个新文件中。我该怎么做?这是我的:
list1 = [x.replace("\n","").replace("/"," ").split(" ") for x in open("dobA.txt")]
list2 = [(i[len(i)-2],i[len(i)-3]) for i in list1]
with open("dobB.txt", "w") as newfile:
newfile.write()
最上面一行代码将日期变成了它们自己的字符串,例如“10”。
第二行代码交换了我需要的数字但只打印出来: [('11', '10'), ('8', '9'), ('9', '7')]
最后两个刚刚写了一个新文件
我如何交换这两个数字并将它们放在一个新文件中?谢谢。
首先,执行此操作:
i[-2]
而不是
i[len(i)-2]
有几个选项可以解决这个问题:
可读但不理解:
with open("old_file.txt") as old_file, open("new_file.txt", "w") as new_file:
for line in old_file:
name, surname, date = line.split()
day, month, year = date.split("/")
print(f"{name} {surname} {month}/{day}/{year}", file=new_file)
正则表达式替换:
import re
from pathlib import Path
text = Path("old_file.txt").read_text()
replaced = re.sub(r"(\d+)/(\d+)/(\d+)", r"//", text)
Path("new_file.txt").write_text(replaced)
如果你真的需要理解:
with open("old_file.txt") as old_file, open("new_file.txt", "w") as new_file:
new_lines = [
f"{text} {date.split('/')[1]}/{date.split('/')[0]}/{date.split('/')[2]}"
for text, date in [line.rsplit(maxsplit=1) for line in old_file]
]
print("\n".join(new_lines), file=new_file)
我想看看这是否可以一次性完成。它可能违背“可读性”。
翻转月份和日期的最简单方法是利用日期时间对象上的 string formatting methods。
有关格式选项,请参阅 Python strftime reference。
from pathlib import Path
import tempfile
from datetime import datetime
import operator as op
# Create temporary files for reading and writing.
_, filename = tempfile.mkstemp()
file_A = Path(filename)
_, filename = tempfile.mkstemp()
file_B = Path(filename)
contents_A = """Adam Brown 10/11/1999
Lauren Marie Smith 9/8/2001
Vincent Guth II 7/9/1980"""
file_A.write_text(contents_A)
# This version requires Python 3.8.
# It uses the newly introduced assignment expression ":=".
# datetime objects have string formatting methods.
file_B.write_text(
"\n".join(# re-join the lines
[
" ".join(# re-join the words
(
# Store the split line into words. Then slice all but last.
" ".join((words := line.split())[:-1]),
# Convert the last word to desired date format.
datetime.strptime(words[-1], "%m/%d/%Y",).strftime("%-d/%-m/%Y",),
)
)
for line in fileA.read_text().splitlines()
]
)
)
print(file_B.read_text())
输出:
Adam Brown 11/10/1999
Lauren Marie Smith 8/9/2001
Vincent Guth II 9/7/1980
如果没有“:=”运算符,问题就多了一点。这意味着必须在理解中调用 line.split()
两次。
file_B.write_text("\n".join([
" ".join(
op.add(
line.split()[:-1],
[
datetime.strptime(
line.split()[-1], "%m/%d/%Y",
).strftime("%-d/%-m/%Y",),
],
)
)
for line in fileA.read_text().splitlines()
]))
print(file_B.read_text())
输出:
Adam Brown 11/10/1999
Lauren Marie Smith 8/9/2001
Vincent Guth II 9/7/1980