将句子的长度附加到文件中
Appending the length of sentences to file
我找到了长度和索引,我想将它们全部保存到新文件中:
示例:索引句子长度
我的代码
file = open("testing_for_tools.txt", "r")
lines_ = file.readlines()
for line in lines_:
lenght=len(line)-1
print(lenght)
for item in lines_:
print(lines_.index(item)+1,item)
输出:
64
18
31
31
23
36
21
9
1
1 i went to city center, and i bought xbox5 , and some other stuff
2 i will go to gym !
3 tomorrow i, sill start my diet!
4 i achive some and i need more ?
5 i lost lots of weights؟
6 i have to , g,o home,, then sleep ؟
7 i have things to do )
8 i hope so
9 o
所需的输出并保存到新文件:
1 i went to city center, and i bought xbox5 , and some other stuff 64
2 i will go to gym ! 18
这可以使用以下代码实现。注意 with ... as f
的使用,这意味着我们不必担心在使用后关闭文件。此外,我使用了 f-strings(需要 Python 3.6)和 enumerate
来获取行号并将所有内容连接成一个字符串,该字符串被写入输出文件。
with open("test.txt", "r") as f:
lines_ = f.readlines()
with open("out.txt", "w") as f:
for i, line in enumerate(lines_, start=1):
line = line.strip()
f.write(f"{i} {line} {len(line)}\n")
输出:
1 i went to city center, and i bought xbox5 , and some other stuff 64
2 i will go to gym ! 18
如果您想根据长度对行进行排序,您可以将以下行放在第一个 with
块之后:
lines_.sort(key=len)
这将给出输出:
1 i will go to gym ! 18
2 i went to city center, and i bought xbox5 , and some other stuff 64
我找到了长度和索引,我想将它们全部保存到新文件中:
示例:索引句子长度
我的代码
file = open("testing_for_tools.txt", "r")
lines_ = file.readlines()
for line in lines_:
lenght=len(line)-1
print(lenght)
for item in lines_:
print(lines_.index(item)+1,item)
输出:
64
18
31
31
23
36
21
9
1
1 i went to city center, and i bought xbox5 , and some other stuff
2 i will go to gym !
3 tomorrow i, sill start my diet!
4 i achive some and i need more ?
5 i lost lots of weights؟
6 i have to , g,o home,, then sleep ؟
7 i have things to do )
8 i hope so
9 o
所需的输出并保存到新文件:
1 i went to city center, and i bought xbox5 , and some other stuff 64
2 i will go to gym ! 18
这可以使用以下代码实现。注意 with ... as f
的使用,这意味着我们不必担心在使用后关闭文件。此外,我使用了 f-strings(需要 Python 3.6)和 enumerate
来获取行号并将所有内容连接成一个字符串,该字符串被写入输出文件。
with open("test.txt", "r") as f:
lines_ = f.readlines()
with open("out.txt", "w") as f:
for i, line in enumerate(lines_, start=1):
line = line.strip()
f.write(f"{i} {line} {len(line)}\n")
输出:
1 i went to city center, and i bought xbox5 , and some other stuff 64
2 i will go to gym ! 18
如果您想根据长度对行进行排序,您可以将以下行放在第一个 with
块之后:
lines_.sort(key=len)
这将给出输出:
1 i will go to gym ! 18
2 i went to city center, and i bought xbox5 , and some other stuff 64