Python not reading the first line of my file - python

I have a homework assignment where the goal is to count the number of times certain words occur in a file, however when I open the file I cannot get it to read the first line of said file.
while True:
try:
File_Name = input("Enter file name ")
with open(File_Name, "r") as File:
print("File opened")
for line in File:
text = File.read()
print("File Read")
replaced = text.replace(".", " ").replace(","," ").replace("!", " ").replace("?", " ").replace(":", " ").replace(";", " ").lower()
print("File edited")
print(replaced)
except:
print("Invalid File Name, please retry")
continue```
This is the text I am using just for testing:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
inciDiDunt uT labOre et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
And this is the output I get:
File opened
File Read
File edited
incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur
excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum ```

You are mixing and matching consumption modes. You should stop that.
with open(File_Name, "r") as File:
print("File opened")
for line in File:
text = File.read()
This block of code:
Opens the file.
Prepares to consume the file line by line (for line in File:).
Consumes all remaining content in a single go (text = File.read()).
You should either:
Consume the file line by line (remove the File.read())
Consume the entire file (remove the unnecessary for loop).

Your for line in File actually read the first line of the file.
So at the first iteration, the first line of your file is stored in the line variable, and text = File.read() reads the rest

Related

How to create a word wrapping program in Python 3.6

I am trying to create a program that simulates word wrapping text found in programs like Word or Notepad. If I have a long text, I would like to print out 64 characters (or less) per line, followed by a newline return, without truncating words. Using Windows 10, PyCharm 2018.2.4 and Python 3.6, I've tried the following code:
long_str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit," \
"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." \
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris" \
"nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in" \
"reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." \
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui" \
"officia deserunt mollit anim id est laborum."
concat_str = long_str[:64] # The first 64 characters
rest_str = long_str[65:] # The rest of the string
rest_str_len = len(rest_str)
while rest_str_len > 64:
print(concat_str.lstrip() + " (" + str(len(concat_str)) + ")" + "\n")
concat_str = rest_str[:64]
rest_str = rest_str[65:]
rest_str_len = len(rest_str)
print(concat_str.lstrip() + " (" + str(len(concat_str)) + ")" + "\n")
print(rest_str.lstrip() + " (" + str(len(rest_str)) + ")")
This is so close, but there are two problems. First, the code truncates off letters at the end or beginning of lines, such as the following output:
# I've added the total len() at the end of each line just to check-sum.
'Lorem ipsum dolor sit amet, consectetur adipiscing elit,sed do e (64)'
'usmod tempor incididunt ut labore et dolore magna aliqua. Ut enim (64)'
'ad minim veniam, quis nostrud exercitation ullamco laborisnisi u (64)'
'aliquip ex ea commodo consequat. Duis aute irure dolor inrepreh (64)'
'nderit in voluptate velit esse cillum dolore eu fugiat nulla par (64)'
'atur. Excepteur sint occaecat cupidatat non proident, sunt in cul (64)'
'a quiofficia deserunt mollit anim id est laborum. (49)'
The second problem is that I need the code to print a newline only after a whole word (or punctuation), instead of chopping up the word at 64 characters.
Use textwrap.wrap:
import textwrap
long_str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit," \
"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." \
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris" \
"nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in" \
"reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." \
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui" \
"officia deserunt mollit anim id est laborum."
lines = textwrap.wrap(long_str, 64, break_long_words=False)
print('\n'.join(lines))
This takes long string and splits it into lines of a particular width. Also, set break_long_words to False to prevent splitting of words.

how to use ttf files to estimate how the browser wraps text in a fixed width div

I would like to estimate the height of a div element containing only text as rendered by a browser. For example, consider this htm file:
<html>
<body>
<div style="position:absolute; top:100pt; left:80pt; width:200pt">
<p style="line-height:16pt; font-size:9pt; font-family:Monospace; font-style:normal; font-weight:normal;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
</body>
</html>
This is my attempt in python:
from PIL import ImageFont
import re
def getHeightOfTextBox(line_height, font_size, ttfFileName, box_width, text):
text = text.strip()
text = re.sub('\s+', ' ', text)
font = ImageFont.truetype(ttfFileName, font_size)
numLines = 1
cursor = 0
spaceWidth = font.getsize(' ')[0]
afterLineBreak = False
for word in text.split(' '):
wordWidth = font.getsize(word)[0]
cursor += wordWidth + (spaceWidth if afterLineBreak else 0)
if cursor > box_width:
print(word)
numLines += 1
afterLineBreak = True
cursor = wordWidth
else:
afterLineBreak = False
cursor += spaceWidth
return numLines * line_height
text = '''
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
'''
print(getHeightOfTextBox(16, 9, "LiberationMono-Regular.ttf", 200, text))
Here is the output of the script:
adipiscing
incididunt
aliqua.
nostrud
nisi
Duis
in
fugiat
occaecat
culpa
id
192
which gives 12 lines in total. Here is how the div element is rendered in my Firefox browser:
which gives 13 lines. In this example, pillow says the width of a character is 5pts, so 0.025 of the width of the div. Using Firefox's inspect element feature, Firefox calculates the width of a character to be 7px and the width of the div to be 266.667px, so 0.02625 the width of the div. At this point, my best guess is that the reason for this discrepancy is that Firefox thinks the width if a character is slightly larger than pillow does. If I change this example by using a font size of 10pts then I get agreement between my code and Firefox.
Is it possible to correct my code to accurately estimate, using the font metric file, the height of the div as rendered by a browser? I know another option is to use a headless browser like PhantomJS in conjunction with Selenium. But I am hoping to avoid this, as I feel it could be over-kill.

Proper word wrapping of long text

I have a 1000 character long text string and I want to split this text in chunks smaller than 100 characters without splitting a whole word (99 characters are fine but 100 not). The wrapping/splitting should only be made on whitespaces:
Example:
text = "... this is a test , and so on..."
^
#position: 100
should be splitted to:
newlist = ['... this is a test ,', ' and so on...', ...]
I want to get a list newlist of the text splitted properly into readable (not word-cropped) chunks. How would you do this?
Use the textwrap module's wrap function. The below example splits the lines 10 characters wide:
In [1]: import textwrap
In [2]: textwrap.wrap("... this is a test , and so on...", 10)
Out[2]: ['... this', 'is a test', ', and so', 'on...']
You can use the textwrap module:
In [2]: import textwrap
In [3]: textwrap.wrap("""Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
...: tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
...: quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
...: consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
...: cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
...: proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
""", 40)
Out[3]:
['Lorem ipsum dolor sit amet, consectetur',
'adipisicing elit, sed do eiusmod tempor',
'incididunt ut labore et dolore magna',
'aliqua. Ut enim ad minim veniam, quis',
'nostrud exercitation ullamco laboris',
'nisi ut aliquip ex ea commodo consequat.',
'Duis aute irure dolor in reprehenderit',
'in voluptate velit esse cillum dolore eu',
'fugiat nulla pariatur. Excepteur sint',
'occaecat cupidatat non proident, sunt in',
'culpa qui officia deserunt mollit anim',
'id est laborum.']
Wordwrap like the other guys said, however for an alternative option:
def splitter(s, n):
for start in range(0, len(s), n):
yield s[start:start+n]
data = "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghij"
for splitee in splitter(data, 10):
print splitee

Split diary file into multiple files using Python

I keep a diary file of tech notes. Each entry is timestamped like so:
# Monday 02012-05-07 at 01:45:20 PM
This is a sample note
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
# Wednesday 02012-06-06 at 03:44:11 PM
Here is another one.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
Would like to break these notes down into individual files based on timestamp headers. e.g. This is a sample note.txt, Here is another really long title.txt. Im sure I would have to truncate the filename at some point, but the idea would be to seed the filename based on the first line of the diary entry.
It doesn't look like I can modify the file's creation date via python, so I would like to preserve the entries timestamp as part of the note's body.
I've got a RegEx pattern to capture the timestamps that suits me well:
#(\s)(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)(\s)(.*)
and can likely use that regex to loop through the file and break each entry down, but im not quite sure how to loop through the diary file and break it out into individual files. There are a lot of examples of grabbing the actual regex pattern, or particular line, but I want to do a few more things here and am having some difficulty peicing it together.
Here is an example of the desired file contents (datestamp + all text up until next datestamp match):
bash$ cat This\ is\ a\ sample\ note.txt
Monday 02012-05-07 at 01:45:20 PM
This is a sample note
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
bash$
Here's the general ;-) approach:
f = open("diaryfile", "r")
body = []
for line in f:
if your_regexp.match(line):
if body:
write_one(body)
body = []
body.append(line)
if body:
write_one(body)
f.close()
In short, you just keep appending all lines to a list (body). When you find a magical line, you call write_one() to dump what you have so far, and clear the list. The last chunk of the file is a special case, because you're not going to find your magical regexp again. So you again dump what you have after the loop.
You can make any transformations you like in your write_one() function. For example, sounds like you want to remove the leading "# " from the input timestamp lines. That's fine - just do, e.g.,
body[0] = body[0][2:]
in write_one. All the lines can be written out in one gulp via, e.g.,
with open(file_name_extracted_from_body_goes_here, "w") as f:
f.writelines(body)
You probably want to check that the file doesn't exist first! If it's anything like my diary, the first line of many entries will be "Rotten day." ;-)
It really doesn't require as much regex as you would think.
First just load the file so you have it based on new lines:
fl = 'file.txt'
with open(fl,'r') as f:
lines = f.readlines()
now just loop through it! Compare each line with the regex you provided, and if it matches, that means it's a new date!
Then you will grab the next non-empty line after that and set it as the name of the file.
Then keep going through and writing lines to that specific file name until you hit another match to your regex, where you know it is now meant to be a new file. Here is the logic loop:
for line in lines:
m = re.match(your regex)
if m:
new_file = True
else:
new_file = False
#now you will know when it's a new entry so you can easily do the rest
Let me know if you need any more of the logic broken down. Hopefully this was helpful
You set the "batch-file" tag in your question, so I wrote a Batch file .bat solution. Here it is:
#echo off
setlocal EnableDelayedExpansion
set daysOfWeek=/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday/Sunday/
for /F "delims=" %%a in (input.txt) do (
if not defined timeStamp (
set timeStamp=%%a
) else if not defined fileName (
set fileName=%%a
(
echo !timeStamp!
echo/
echo !fileName!
echo/
) > "!fileName!.txt"
) else (
for /F "tokens=2" %%b in ("%%a") do if "!daysOfWeek:/%%b/=!" equ "%daysOfWeek%" (
echo %%a>> "!fileName!.txt"
) else (
set timeStamp=%%a
set "fileName="
)
)
)
For example:
C:\Users\Antonio\Documents\test
>dir /B
input.txt
test.bat
C:\Users\Antonio\Documents\test
>test
C:\Users\Antonio\Documents\test
>dir /B
Here is another one.txt
input.txt
test.bat
This is a sample note.txt
C:\Users\Antonio\Documents\test
>type "Here is another one.txt"
# Wednesday 02012-06-06 at 03:44:11 PM
Here is another one
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
C:\Users\Antonio\Documents\test
>type "This is a sample note.txt"
# Monday 02012-05-07 at 01:45:20 PM
This is a sample note
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Python html2text adds random \n

When using the html2text python package to convert html to markdown it adds '\n' to the text. I also see this behaviour when trying the demo at http://www.aaronsw.com/2002/html2text/
Is there any way to turn this off? Of course I can remove them myself, but there might be occurrences of '\n' in the original text which I don't want to remove.
html2text('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.')
u'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\nconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\ncillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\nproident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n\n'
In the latest version of html2text do this:
import html2text
h = html2text.HTML2Text()
h.body_width = 0
note = h.handle("<p>Hello, <a href='http://earth.google.com/'>world</a>!")
This removes the word wrapping that html2text otherwise does
Looking at the source to html2text.py, it looks like you can disable the wrapping behavior by setting BODY_WIDTH to 0. Something like this:
import html2text
html2text.BODY_WIDTH = 0
text = html2text.html2text('...')
Of course, resetting BODY_WIDTH globally changes the module's behavior. If I had a need to access this functionality, I'd probably seek to patch the module, creating a parameter to html2text() to modify this behavior per-call, and provide this patch back to the author.

Categories

Resources