Python - horizontal output, with braquets, commas and quotations marks - python-3.x

s = "That that occurs sometimes. It sometimes means that which, and sometimes just that"
target = "that"
words = s.split()
b = []
for i,w in enumerate(words):
if w == target:
if i > 0:
b = words[i-1]
print([b].sep="",end",")
"I used, end=",sep=",but nothing worked.I need the output horizontally, with square brackets, commas and quotations marks. the brackets appear in the middle, and a comma at the end."
"Current output"
['That'],['means'],['just'],
"I need this output"
['That','means','just']

try this code it will work fine
s = "That that occurs sometimes. It sometimes means that which, and sometimes just that"
target = "that"
words = s.split()
b = []
for i,w in enumerate(words):
if w == target:
if i > 0:
b.append(words[i-1])
print(b,sep="")

Related

How do I use text replace with plural/singular strings

I'm trying to replace words from strings using text.replace().
It works well till the replace words with plurals are used as follows:
def replacing():
texter = []
del texter[:]
repl = ['diabetes', 'mellitus', 'dm', ]
it = ''
try:
it = iter(np.array(repl))
except:
pass
txt = "tell me if its can also cause coronavirus"
for i in range(len(np.array(repl1))):
try:
p = it.__next__()
x = txt.replace("its", p)
texter.append(x)
x = txt.replace("it", p)
texter.append(x)
xxx = txt.replace("them", p)
texter.append(xxx)
xxxx = txt.replace("the same", p)
texter.append(xxx)
xxxxx = txt.replace("this", p)
texter.append(xxx)
except StopIteration:
break
mm = list(OrderedDict.fromkeys(texter))
print (mm)
replacing()
This is the result of this code:
['tell me if diabetes can also cause coronavirus', 'tell me if diabetess can also cause coronavirus', 'tell me if mellitus can also cause coronavirus', 'tell me if mellituss can also cause coronavirus', 'tell me if dm can also cause coronavirus', 'tell me if dms can also cause coronavirus']
Notice the misspell replaced words as 'diabetess' instead of 'diabetes', 'mellituss' instead of mellitus and 'dms' instead of 'dm'.
I noted the keywords 'it and its', since are similar end up bringing the errors.
How can I avoid this
The issue is that you are replacing "it" and "its" separately. txt.replace("it", p) creates a copy of txt with "it" replaced by p, so "its" becomes "diabetess". Use the re module to specify that you want to replace "it" or "its". Your for loop would look like this:
for i in range(len(np.array(repl))):
try:
p = it.__next__()
x = re.sub("its|it", p, txt)
texter.append(x)
xxx = txt.replace("them", p)
texter.append(xxx)
xxxx = txt.replace("the same", p)
texter.append(xxx)
xxxxx = txt.replace("this", p)
texter.append(xxx)
except StopIteration:
break

Python: Insert space between every element in a list with one line description in for loop

I am trying to write a simple Encrype and Decrype system. I have a syntax question like the topic above, please take a look.
def en_num(pw):
en1 = [int(x) for x in pw]
for i in en1:
numstr = "".join(bin(int(i))[2:])
numstr += " "
return numstr
For example, input is "1 2", the output will be "1 10"
This can geve me the right output, however, I am trying to write this for loop in one line, like this
def en_num(pw):
en1 = [int(x) for x in pw]
numstr = "".join(bin(int(i))[2:] for i in en1)
return numstr
I don't know how to add the space between in this syntax, the result is "110"
Please take a look, thanks!
Try adding a space between the quotes on your join statement:
numstr = " ".join(bin(int(i))[2:] for i in en1)
That will separate each number.

How would I reverse each word individually rather than the whole string as a whole

I'm trying to reverse the words in a string individually so the words are still in order however just reversed such as "hi my name is" with output "ih ym eman si" however the whole string gets flipped
r = 0
def readReverse(): #creates the function
start = default_timer() #initiates a timer
r = len(n.split()) #n is the users input
if len(n) == 0:
return n
else:
return n[0] + readReverse(n[::-1])
duration = default_timer() - start
print(str(r) + " with a runtime of " + str(duration))
print(readReverse(n))
First split the string into words, punctuation and whitespace with a regular expression similar to this. Then you can use a generator expression to reverse each word individually and finally join them together with str.join.
import re
text = "Hello, I'm a string!"
split_text = re.findall(r"[\w']+|[^\w]", text)
reversed_text = ''.join(word[::-1] for word in split_text)
print(reversed_text)
Output:
olleH, m'I a gnirts!
If you want to ignore the punctuation you can omit the regular expression and just split the string:
text = "Hello, I'm a string!"
reversed_text = ' '.join(word[::-1] for word in text.split())
However, the commas, exclamation marks, etc. will then be a part of the words.
,olleH m'I a !gnirts
Here's the recursive version:
def read_reverse(text):
idx = text.find(' ') # Find index of next space character.
if idx == -1: # No more spaces left.
return text[::-1]
else: # Split off the first word and reverse it and recurse.
return text[:idx][::-1] + ' ' + read_reverse(text[idx+1:])

Finding the "difference" between two string texts (Lua example)

I'm trying to find the difference in text between two string values in Lua, and I'm just not quite sure how to do this effectively. I'm not very experienced in working with string patterns, and I'm sure that's my downfall on this one. Here's an example:
-- Original text
local text1 = "hello there"
-- Changed text
local text2 = "hello.there"
-- Finding the alteration of original text with some "pattern"
print(text2:match("pattern"))
In the example above, I'd want to output the text ".", since that's the difference between the two texts. Same goes for cases where the difference could be sensitive to a string pattern, like this:
local text1 = "hello there"
local text2 = "hello()there"
print(text2:match("pattern"))
In this example, I'd want to print "(" since at that point the new string is no longer consistent with the old one.
If anyone has any insight on this, I'd really appreciate it. Sorry I couldn't give more to work with code-wise, I'm just not sure where to begin.
Just iterate over the strings and find when they don't match.
function StringDifference(str1,str2)
for i = 1,#str1 do --Loop over strings
if str1:sub(i,i) ~= str2:sub(i,i) then --If that character is not equal to it's counterpart
return i --Return that index
end
end
return #str1+1 --Return the index after where the shorter one ends as fallback.
end
print(StringDifference("hello there", "hello.there"))
local function get_inserted_text(old, new)
local prv = {}
for o = 0, #old do
prv[o] = ""
end
for n = 1, #new do
local nxt = {[0] = new:sub(1, n)}
local nn = new:sub(n, n)
for o = 1, #old do
local result
if nn == old:sub(o, o) then
result = prv[o-1]
else
result = prv[o]..nn
if #nxt[o-1] <= #result then
result = nxt[o-1]
end
end
nxt[o] = result
end
prv = nxt
end
return prv[#old]
end
Usage:
print(get_inserted_text("hello there", "hello.there")) --> .
print(get_inserted_text("hello there", "hello()there")) --> ()
print(get_inserted_text("hello there", "hello htere")) --> h
print(get_inserted_text("hello there", "heLlloU theAre")) --> LUA

Apply backspace within a string

I have a string which includes backspace. Displaying it to the commandline will 'apply' the backspaces such that each backspace and the non-backspace character which immediately precedes it cannot be seen:
>> tempStr = ['aaab', char(8)]
tempStr =
aaa
Yet the deletion operation operation only happens when displaying the string. It still has the backspace character, and the 'b', inside it:
>> length(tempStr)
ans =
5
I'm looking for a minimal (ideally some sort of string processing built in) function which applies the backspace operation:
>>f(tempStr)
ans =
'aaa'
It may also help to know that I have an enumerations class over the alphabet 'a' to 'z' plus ' ' and backspace (to store my own personal indexing of the letters, images associated with each etc.). It'd be real spiffy to have this backspace removal operation be a method of the superclass that acts on a vector of its objects.
You can do it with a simple function using a while loop:
function s = printb(s)
while true
% Find backspaces
I = strfind(s, char(8));
% Break condition
if isempty(I), break; end
% Remove elements
if I(1)==1
s = s(2:end);
else
s(I(1)-1:I(1)) = [];
end
end
and the test gives:
s = [char(8) 'hahaha' char(8) char(8) '!'];
numel(s) % returns 10
z = printb(s) % returns 'haha!'
numel(z) % returns 5
This is not really "minimal", but as far as my knowlegde goes I don't think this is feasible with regular expressions in Matlab.
Best,
Your problem can be solved very elegantly using regular expressions:
function newStr = applyBackspaces(tempStr)
newStr = tempStr;
while (sum(newStr==char(8))>0) % while there is at least one char(8) in newStr do:
tmp = newStr; % work on previous result
if (tmp(1) == char(8)) % if first character is char(8)
newStr = tmp(2:end); % then suppress first character
else % else delete all characters just before a char(8)
newStr = regexprep(tmp,[ '.' char(8)],''); % as well as char(8) itself.
end
end
end
In essence, what my function does is delete the character just before the backspace until there are no more backspaces in your input string tempStr.
To test if it works, we check the output and the length of the string:
>> tempStr = ['abc', char(8), 'def', char(8), char(8), 'ghi']
tempStr =
abdghi
>> length(tempStr)
ans =
12
>> applyBackspaces(tempStr)
ans =
abdghi
>> length(applyBackspaces(tempStr))
ans =
6
Hence, tempStr and applyBackspaces(tempStr) show the same string, but applyBackspaces(tempStr) is the same length as the number of characters displayed.

Resources