如何在每一行的开头添加字符串?
How can i add string at the beginning each line?
我需要在列表中的每行 id 的开头添加五次。
file_id
赞
5
8
6
9
text_file
喜欢
pla pla pla
text text text
dsfdfdfdfd
klfdklfkdkf
poepwoepwo
lewepwlew
结果应该是
5 pla pla pla
5 text text text
5 dsfdfdfdfd
5 klfdklfkdkf
5 poepwoepwo
8 lewepwlew
等等..id的数量等于5000个id,文本等于25000个句子..每个id将有五个句子。我试着做类似的事情
import fileinput
import sys
f = open("id","r")
List=[]
for id in f.readlines():
List.append(id)
file_name = 'text.txt'
with open(file_name,'r') as fnr:
text = fnr.readlines()
i=0
text = "".join([List[i]+" " + line.rstrip() for line in text])
with open(file_name,'w') as fnw:
fnw.write(text)
但有结果
5
pla pla pla5
text text text5
dsfdfdfdfd5
klfdklfkdkf5
poepwoepwo5
lewepwlew5
而不是:
i=0
text = "".join([List[i]+" " + line.rstrip() for line in text])
你可以试试:
new_text = []
for i, line in enumerate(text):
new_text.append(List[i % 5] + " " + line.rstrip())
然后将new_text
写入文件。
你可以试试这个:虽然我还没有测试过
lst = []
with open("id","r") as f:
ids = f.read().split('\n')
file_name = 'text.txt'
with open(file_name,'r') as fnr:
text = fnr.read().split('\n')
counter = 0
for id_num in ids:
for _ in range(5):
if counter >= len(text):
break
lst.append(id_num + " " + text[counter])
counter += 1
text = '\n'.join(lst)
with open(file_name,'w') as fnw:
fnw.write(text)
输出:
1 pla pla pla
1 text text text
1 dsfdfdfdfd
1 klfdklfkdkf
1 poepwoepwo
2 lewepwlew
2
我需要在列表中的每行 id 的开头添加五次。
file_id
赞
5
8
6
9
text_file
喜欢
pla pla pla
text text text
dsfdfdfdfd
klfdklfkdkf
poepwoepwo
lewepwlew
结果应该是
5 pla pla pla
5 text text text
5 dsfdfdfdfd
5 klfdklfkdkf
5 poepwoepwo
8 lewepwlew
等等..id的数量等于5000个id,文本等于25000个句子..每个id将有五个句子。我试着做类似的事情
import fileinput
import sys
f = open("id","r")
List=[]
for id in f.readlines():
List.append(id)
file_name = 'text.txt'
with open(file_name,'r') as fnr:
text = fnr.readlines()
i=0
text = "".join([List[i]+" " + line.rstrip() for line in text])
with open(file_name,'w') as fnw:
fnw.write(text)
但有结果
5
pla pla pla5
text text text5
dsfdfdfdfd5
klfdklfkdkf5
poepwoepwo5
lewepwlew5
而不是:
i=0
text = "".join([List[i]+" " + line.rstrip() for line in text])
你可以试试:
new_text = []
for i, line in enumerate(text):
new_text.append(List[i % 5] + " " + line.rstrip())
然后将new_text
写入文件。
你可以试试这个:虽然我还没有测试过
lst = []
with open("id","r") as f:
ids = f.read().split('\n')
file_name = 'text.txt'
with open(file_name,'r') as fnr:
text = fnr.read().split('\n')
counter = 0
for id_num in ids:
for _ in range(5):
if counter >= len(text):
break
lst.append(id_num + " " + text[counter])
counter += 1
text = '\n'.join(lst)
with open(file_name,'w') as fnw:
fnw.write(text)
输出:
1 pla pla pla
1 text text text
1 dsfdfdfdfd
1 klfdklfkdkf
1 poepwoepwo
2 lewepwlew
2