My code gets the Content of the Message like so (works fine):
try:
s, message=nachricht.split("'content': '")
message, s=message.split("', 'channel_id'")
except:
message="."
Now in the Result we get a Variable like this:
Hello i\nam\nDeployd
or
Hello i
am
Deployd.
This is the Second part it uses the Variable to post it to Discord:
payload=json.dumps({
"content": f"{message}\n{attachments}"
, "username": f"{user_name}#{user_discrm}, {user_id}{namehookidentifiyer}", "avatar_url": f"https://cdn.discordapp.com/avatars/{user_id}/{avatar_code}.png?size=4096"})
req = requests.post(f"{webhook}", data=payload.encode(),headers=headers)
while req.status_code==429:
time.sleep(1)
req = requests.post(f"{webhook}", data=payload.encode(), headers=headers)*
We only care about the content Variable right here so if as shown the content=
f"{message}\n{attachments}"
the \n used in the Middle works just like it should.
But the \n of the message Variable works like it is \\n not \n so the outcome is:
message \n variable
attachments variable
i want that \n to be a new line, i hope you understood everything please help me.
-------------------------------------------
I tried to not use the {message} instead only use content=message
that got the same outcome (with the \n being displayed)
How you may have read if the \n is defined in the content: "\n" without a variable it works fine so its not like \n cant work
I also printed the Varables after they were made and after send to discord
it always was \n not \\n so it technically should have worked
Also the attachments Variable also has \n newlines and that works even though its a Variable used just like the content one i think thats because the \n inside the attachments variable is defined in the String not from outside:
attachments=f"{attachments}\n{value}"
The \n's from the content are split out of the output of a file:
datei = open(f'./data/{guildname}/{kategorie}/{channelname}.txt','r')
nachrichten=datei.read()
for nachricht in nachrichten:
if len(nachricht)>=10:
try:
s, message=nachricht.split("'content': '")
message, s=message.split("', 'channel_id'")
except:
message="."
Fixed it by adding this code:
s, message1=nachricht.split("'content': '")
message1, s=message1.split("', 'channel_id'")
message=""
for value in message1.split('\\n'):
message=f"{message}\n{value}"
Chanched the massage Variable to massage1
then splitting it on every \n and putting the split parts together but with a \n inside the message="\n" so its not from an outside variable, i figured this out by looking at the attachments because they worked fine, then i though of a solution to bring the \n outside a variable into the code.
Related
I'm trying to parse a webpage:However, I want to only focus on text within the div tag labelled "class='body conbody'". I want my program to look inside of this tag and output the text exactly like how they appear on the webpage.
Here is my code so far:
pres_file = directory + "\\" + pres_number + ".html"
with open(pres_file) as html_file:
soup = BeautifulSoup(html_file, 'html.parser')
desiredText = soup.find('div', class_='body conbody')
for para in desiredText.find_all('p'):
print(para.get_text())
The problem with my current code is that whenever I try to print the paragraphs, (a), (1), (2), (b), and (c) are always formatted with a lot of unnecessary newlines and additional spaces after it. However, I would like for it to output text that is equivalent to how it looks on the webpage. How can I change my code to accomplish this?
I want my program to look inside of this tag and output the text exactly like how they appear on the webpage.
The browser does a lot of processing to display a web page. This includes removing extra spaces. Additionally, the browser developer tools show a parsed version of the HTML as well as potential additions from dynamic JavaScript code.
On the other hand, you are opening a raw text file and get the text as it is, including any formatting such as indentation and line breaks. You will need to process this yourself to format it the way you want when you output it.
There are at least two things to look for:
Is the indentation tab or space characters? By default print() represents a tab as 8 spaces. You can either replace the tabs with spaces to reduce the indentation or you can use another output method that allows you to configure specify how to show tabs.
The strings themselves will include a newline character. But then print() also adds a line break. So either remove the newline character from each string or do print(para.get_text(), end='') to disable print adding another newline.
You can use strip() on strings, like para.get_text().strip(). This will remove any whitespaces before and after the string.
You can use either lstrip() and rstrip() to remove only the exceeding whitespaces from the left or right side of the string.
s = " \t \n\n something \t \n "
print(s.strip()) # 'something'
print(s.lstrip()) # 'something \t \n '
print(s.rstrip()) # ' \t \n\n something'
Would something like this work:
Strip left and right of the p
Indent the paragraph with 1em (so 1 times the font size)
Newline each paragraph
font_size = 16 # get the font size
for para in desiredText.find_all('p'):
print(font_size * " " + para.get_text().strip(' \t\n\r') + "\n")
I have created a python script for sending a tweet out to twitter. I am having an issue with sending a carriage return / line break. Normally I would like the command \n in python but this doesn't work with tweepy and it send the text to twitter including the \n.
The end of my script looks like this:
phrase = "Hello World! \n I am sending a tweet from a bot!"
api.update_status(phrase)
and the result on twitter is:
Hello World! \n I am sending a tweet from a bot!
and what I want is:
Hello World!
I am sending a tweet from a bot!
How can I do this with my script?
That's unusual, what you tried should be working.
For whatever reason, it doesn't seem to be. This should work instead:
phrase = """
Hello World!
I am sending a tweet from a bot!
"""
api.update_status(phrase)
I'm sorry for the late response, but I was struggling with this until I figured out the solution:
create_tweet(text=message.replace("\\n", "\n"))
That replaces the escaped newline with a true newline character.
I haven't tested it out with api.update_status, but it still should work nevertheless.
For a pre downloaded html file,i want to replace multiple \n with a new line.
i have tried,
html = html.replace('\n',''), but doesn't work.
Is there any other work around?
The line drop may be represented by \r
print (html.replace("\n", "").replace("\r", ""))
When I am entering a string input that contains line breaks, Python thinks that I have pressed Enter and continues to the next commands.
How can I put \n when Enter is pressed, to send the rest to an extra line?
In python, if you have a paragraph to execute without a break,
Use triple quotes .
Here's is an example :
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print (para_str)
To continue processing of the same command to the next line, add a backslash ('\') before a '\n'
One very stupid thing happens when I modify a string that contained newline characters within it.
After modifying the string variable, I print it. It successfully shows that the new line character has been removed.
When I write the string variable to a file, it prints the new line character there.
I spent hours figuring this out!
import os
import csv
s = "I want this \n new line removed"
s = s.replace("\n", "")
print(s)
file = open('my_file.tsv', 'w')
file.write(s)
file.close()
The above is a sample code. If you run this code, it will run. The string in my real project is a text dynamically fetched from a mysql database -- which is being modified. That contains one or more \n characters within it.
If in the above code, I try replacing that text obtained from the database in a hardcoded manner and running it, it throws me an error saying "EOL while scanning string lateral"
Can you please help me clean this text into something consumable?
Removal of '\r\n' worked!! Thanks a lot #abarnert for the suggestion.
The text wasn't visible to me in code form. It was raw text fetched from db. The raw text just looked like a paragraph with multiple newlines. Hence, I wasn't able to provide real text