简体   繁体   English

如何在每行的开头添加字符串?

[英]How can i add string at the beginning each line?

I need to add at beginning of each line id from a list five times.我需要在列表中每行 id 的开头添加五次。 file_id like file_id喜欢

5
8
6
9

text_file like text_file喜欢

pla pla pla 
text text text 
dsfdfdfdfd
klfdklfkdkf
poepwoepwo
lewepwlew

the result should be结果应该是

5 pla pla pla 
5  text text text
5  dsfdfdfdfd
5  klfdklfkdkf
5  poepwoepwo
8  lewepwlew

and so on .. the number of ids equals 5000 ids and text equals 25000 sentences .. every id will be with five sentences.依此类推.. id 的数量等于 5000 个 id,文本等于 25000 个句子 .. 每个 id 将包含五个句子。 i tried to do something like that我试图做这样的事情

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)

but got results但得到了结果

 5
 pla pla pla5
 text text text5
 dsfdfdfdfd5
 klfdklfkdkf5
 poepwoepwo5
 lewepwlew5 

Instead of:代替:

i=0
text = "".join([List[i]+" " + line.rstrip()  for line in text])

You can try:你可以试试:

new_text = []
for i, line in enumerate(text):
    new_text.append(List[i % 5] + " " + line.rstrip())

And then write new_text to the file.然后将new_text写入文件。

you can try this: I haven't tested it yet though你可以试试这个:虽然我还没有测试过

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)

output:输出:

1 pla pla pla
1 text text text
1 dsfdfdfdfd
1 klfdklfkdkf
1 poepwoepwo
2 lewepwlew
2 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM