Home > database >  string in file on one line
string in file on one line

Time:06-01

I have a file like this

A0001
/1536.
/1537.
/1511.
/1451.
/1388.
/1323.
/1322.


# And so on...

I used json .format to make it like this

<div ><img  title="" src="resources/images/thumb/A0001
.png"width="64" height="64"></div>
<div ><img  title="" src="resources/images/thumb/1536
.png"width="64" height="64"></div>
<div ><img  title="" src="resources/images/thumb/1537
.png"width="64" height="64"></div>
<div ><img  title="" src="resources/images/thumb/1511
.png"width="64" height="64"></div>
<div ><img  title="" src="resources/images/thumb/1451
.png"width="64" height="64"></div>
<div ><img  title="" src="resources/images/thumb/1388
.png"width="64" height="64"></div>
<div ><img  title="" src="resources/images/thumb/1323
.png"width="64" height="64"></div>
<div ><img  title="" src="resources/images/thumb/1322
.png"width="64" height="64"></div>


#And so on 

But that's not the output I was looking for, what I'm looking for is this:

<div ><img  title=""src="resources/images/thumb/1242.png"width="64" height="64"></div>
<div ><img  title=""src="resources/images/thumb/1536.png"width="64" height="64"></div>
<div ><img  title=""src="resources/images/thumb/1242.png"width="64" height="64"></div>

I want every string to be on one line. as I'm new to python and I don't know what to search for to get an answer to my question, This is my code

import re
import pyperclip
import json

def remove_punc(string):
    punc = '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
    for ele in string:  
        if ele in punc:  
            string = string.replace(ele, "") 
    return string




d = '<div ><img  title="" src="resources/images/thumb/{}.png"></div>'

rex = re.compile(p)


f= open('txte.txt', 'r')
lines = f.readlines() 



results = [remove_punc(i) for i in lines]

f.close()

fp= open("data1.txt", "w")
for item in results:
    print(d.format(item), file=fp)

fp.close()


CodePudding user response:

It seems like you are missing an action to strip the new line.

You could add a replace after the first replace like this

def remove_punc(string):
    punc = '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
    for ele in string:  
        if ele in punc:  
            string = string.replace(ele, "")**.replace('\n','')**
    return string

Maybe take a look at this question.

CodePudding user response:

You have to remove the newline character ('\n') from the end of each line. This can be done with strip.

I rewrote the remove_punc function to use translate to make it faster.

This replaces your full code example.

def remove_punc(text):
    punc = '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
    return text.translate(str.maketrans('', '', punc)).strip()

with open('txte.txt') as names, open("data1.txt", "w") as target:
    for name in names:
        target.write(f'<div ><img  title="" src="resources/images/thumb/{remove_punc(name)}.png"></div>\n')
  • Related