How to delete a textline with matched text in QPlainTextEdit? - python

Below lines are in A QPlainTextEdit:
I want to delete a matched line with line variable help.
For example, I want to delete
line 2 s44 grade
with the help of line variable(line = "line 2")
I am able to delete the particular text with below code:
item = "line 2"
text = self.project_length_lanes_plainedit.toPlainText()
text = text.replace(item, '')
_list = text.split()
text = '\n'.join(_list)
self.project_length_lanes_plainedit.setPlainText(text)
but I want to delete the entire line. How can I do that?

you have 2 basic options:
use regexp to match whole line in your replace, then splitting lines is not necessary
split to list first and remove matching line from list, and in the end join list as you did
EDIT:
import re
x = """
line1: abc
line2: def
line3: ghi
"""
print("regex:")
print(re.sub(r'line2.*', '', x)) # note: this leaves empty line
print("regex2:")
print(re.sub(r'line2.*\n', '', x))
print("list:")
print('\n'.join([line for line in x.split('\n') if "line2" not in line]))

I tried as below working:
item = "line 2"
text = self.project_length_lanes_plainedit.toPlainText()
for l in text.split('\n'):
if item in l:
text = text.replace(l, '')
_list = text.split('\n')
_list = [ i for i in _list if i ]
text = '\n'.join(_list)
self.project_length_lanes_plainedit.setPlainText(text)

Related

Swap quoted word in random position with last word in Python

I have a txt file with lines of text like this, and I want to swap the word in
quotations with the last word that is separated from the sentence with a tab:
it looks like this:
This "is" a person are
She was not "here" right
"The" pencil is not sharpened a
desired output:
This "are" a person is
She was not "right" here
Some ideas:
#1: Use Numpy
Seperate all the words by whitespace with numpy-> ['This','"is"','a','person',\t,'are']
Problems:
How do I tell python the position of the quoted word
How to convert the list back to normal text. Concatenate all?
#2: Use Regex
Use regex and find the word in ""
with open('readme.txt','r') as x:
x = x.readlines()
swap = x[-1]
re.findall(\"(\w+)\", swap)
Problems:
I don't know what to read the txt file with regex. most examples I see here will assign the entire sentence to a variable.
Is it something like this?
with open('readme.txt') as f:
lines = f.readlines()
lines.findall(....)
Thanks guys
You don't really need re for something this trivial.
Assuming you want to rewrite the file:
with open('foo.txt', 'r+') as txt:
lines = txt.readlines()
for k, line in enumerate(lines):
words = line.split()
for i, word in enumerate(words[:-1]):
if word[0] == '"' and word[-1] == '"':
words[i] = f'"{words[-1]}"'
words[-1] = word[1:-1]
break
lines[k] = ' '.join(words[:-1]) + f'\t{words[-1]}'
txt.seek(0)
print(*lines, sep='\n', file=txt)
txt.truncate()
This is my solution:
regex = r'"[\s\S]*"'
import re
file1 = open('test.txt', 'r')
count = 0
while True:
# Get next line from file
line = file1.readline()
# if line is empty
# end of file is reached
if not line:
break
get_tab = line.strip().split('\t')[1]
regex = r'\"[\s\S]*\"'
print("original: {} mod ----> {}".format(line.strip(), re.sub(regex, get_tab, line.strip().split('\t')[0])))
Try:
import re
pat = re.compile(r'"([^"]*)"(.*\t)(.*)')
with open("your_file.txt", "r") as f_in:
for line in f_in:
print(pat.sub(r'"\3"\2\1', line.rstrip()))
Prints:
This "are" a person is
She was not "right" here
"a" pencil is not sharpened The
I guess this is also a way to solve it:
Input readme.txt contents:
This "is" a person are
She was not "here" right
"The" pencil is not sharpened a
Code:
import re
changed_text = []
with open('readme.txt') as x:
for line in x:
splitted_text = line.strip().split("\t") # ['This "is" a person', 'are'] etc.
if re.search(r'\".*\"', line.strip()): # If a quote is found
qouted_text = re.search(r'\"(.*)\"', line.strip()).group(1)
changed_text.append(splitted_text[0].replace(qouted_text, splitted_text[1])+"\t"+qouted_text)
with open('readme.txt.modified', 'w') as x:
for line in changed_text:
print(line)
x.write(line+"\n")
Result (readme.txt.modified):
Thare "are" a person is
She was not "right" here
"a" pencil is not sharpened The

Why replacing strings from dictionary produce empty file

I'm trying to replace some strings with other strings in a text file,
but the code produce empty file (file size is 0)
what am I missing ?
emotion_list = {":-)" : "happy-similey", \
":-(": "sad-similey"}
for line in fileinput.input(file_name, inplace=True):
if not line:
continue
for f_key, f_value in emotion_list.items():
if f_key in line:
line = line.replace(f_key, f_value)
You missing the print statement to send replaced line to your file:
for line in fileinput.input(file_name, inplace=True):
if not line:
continue
for f_key, f_value in emotion_list.items():
if f_key in line:
line = line.replace(f_key, f_value)
print(line, end="") # print without newline
In your code you are maching file line with word.So split line by spaces to get words (If you do match word in a entire line then you have to give the no.of occurences you want to replace and no of occurences is dynamic.You don't how much occurences would be there in file in a real scenarios)
emotion_list = {":-)" : "happy-similey", \
":-(": "sad-similey"}
file="I am not really :-) but I am not :-( too "
for line in file.split():
for f_key, f_value in emotion_list.items():
if f_key == line:
file=file.replace(line, f_value,1)
print(file)
output
I am not really happy-similey but I am not sad-similey too
This is basically the problem you are facing:
lst = ["abc", "acd", "ade"]
for x in lst:
x = x.replace("a", "x")
print(lst) # ["abc", "acd", "ade"]
Instead, you should replace the ith element of the list:
lst = ["abc", "acd", "ade"]
for i, x in enumerate(lst):
lst[i] = x.replace("a", "x")
print(lst) # ['xbc', 'xcd', 'xde']
This is happening because strings are immutable in Python!

Python search for patterns in all lines, export only lines with results

I would like to search for strings that match a pattern in a text file and export only the matched strings
k=''
regex = re.compile(r'[a-zA-Z]{2}\d{8}')
with open(file, 'r') as f:
for line in f:
line = line.replace(',', '')
line = line.replace('.', '')
k = regex.findall(line)
#k.append(line)
if not k=='':
position=True
else:
position=False
if position==True:
print(k)
Somehow my code doesn't work, it always returns the following output:
[] [] [] [] [] [] [] ['AI13933231'] [] [] [] [] []
I want the output to contain only the matched strings. Thank you!
The reason why there are empty array literals [] is because this line actually exists, but is either empty (containing just \n) or does not match the regex '[a-zA-Z]{2}\d{8}'. And please note that regex.findall(line) returns an list, so if the regex did not find any that matches, it is an empty list.
Your main error happened in this section: if not k=='':. Note k is an list.
Consider this code:
import re
k=''
regex = re.compile(r'[a-zA-Z]{2}\d{8}')
with open("omg.txt", 'r') as f:
for line in f:
line = line.replace(',', '')
line = line.replace('.', '')
k = regex.findall(line)
#k.append(line)
position = False
if str(k) != '[]': # The `[]` is just the string representation of an empty array
position=True
print(k)
else:
position=False
Given the file (Text after # are ignored, not part of the file)
AZ23153133
# Empty line
AB12355342
gz # No match
XY93312344
The output would be
['AZ23153133']
['AB12355342']
['XY93312344']

Replace words within a string in python

I am a very beginning programmer looking for some help with what is probably a very simple problem. I am trying to write a program that will read a .txt file and then replace any words with an 'e' in them with 'xxxxx'.
Here is what I have so far:
def replace_ewords(text):
ntext = text.replace('e', 'xxxxx')
def main():
filename = "gb.txt"
text = readfile(filename)
new_text = replace_ewords(text)
print(new_text)
main()
Could someone help me with this any give me any critques/pointers?
def replace_ewords(text):
words = []
text = text.split(' ')
for word in text:
if "e" in text:
words.append("x"*len(text))
else:
words.append(text)
return " ".join(words)
with open('filename') as f: # Better way to open files :)
line_list = []
for line in file: # iterate line by line
word_list = []
for word in line.split() # split each line into words
if 'e' in word:
word = 'xxxxx' # replace content if word has 'e'
word_list.append(word) # create new list for the word content in new file
line_list.append(' '.join(word_list)) # list of modified line
# write this content to the file
One line for the loops can be written in the form of list comprehension as:
[' '.join([('xxxx' if 'e' in word else word) for word in line]) for line in file.readlines()]
one liner:
print "\n".join([" ".join([[word, "xxx"]["e" in word] for word in line.split()]) for line in open("file").readlines()])

Turning a text file with words and their positions into a sentence

Say I had a text file with some comments, and then keys and values like so:
# The following is
# a list of words and their positions
I: 1
like: 2
to: 3, 5
go: 4
cafes: 6
How would I go about turning this into a sentence ('I like to go to cafes')? I supposed I should try to turn the text into a dictionary first, but was already having trouble removing comments and splitting it into keys and values...
Any help would be great!
Read the file, appending the word and positions as tuples to a list. Then sort that list, remove the indices and join the words:
with open(inputfilename) as inputfile:
words = []
for line in inputfile:
line = line.strip()
if not line or line.startswith('#'):
continue
word, positions = line.split(':')
words.extend((int(p), word) for p in positions.split(','))
print ' '.join([w for p, w in sorted(words)])
Demo:
>>> with open(inputfilename) as inputfile:
... words = []
... for line in inputfile:
... line = line.strip()
... if not line or line.startswith('#'):
... continue
... word, positions = line.split(':')
... words.extend((int(p), word) for p in positions.split(','))
...
>>> print ' '.join([w for p, w in sorted(words)])
I like to go to cafes
step 1 read the content into a dict
step 2 the sorted for sort the content in dict.
shep3 then finally fetch the value using foreach and then concatenate by + to produce sentence .

Categories

Resources