What does line_spoken do in the program [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Can someone please explain this program, I don't understand where role, line-spoken come from
>>> data = open('sketch.txt')
>>> for each_line in data: // stores each line from the sketch file in each_line
... (role, line_spoken) = each_line.split(':')
... print(role, end='')
... print(' said: ', end='')
... print(line_spoken, end='')

You are looking at a tuple assignment.
The right-hand side expression is expected to have resulted in a sequence of two elements, and these two elements are assigned to the two named targets on the left hand side.
In other words, .split(:) is expected to return two values, and those two values are assigned to the variables role and line_spoken. Most likely, the lines in the file contain text like hamlet:To be or not to be, that is the question\n.
If each_line.split(':') does not return two values, an exception will be raised instead.

role and line_spoken are variables, which are populated with strings read from the file sketch.txt. sketch.txt contains colon-separated pairs of words or phrases, and role and line_spoken get those words/phrases.
The split() function returns a "tuple", which is "unpacked" into your two variables.
(Note that the parentheses around (role, line_spoken) are unnecessary.)

Related

Matching two comma seperated strings in Python and correct position counts [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Improve this question
Hope get assistance on the below problem.
Python having more in-built sequence matcher functions. Whether the following requirement can be done through any built-in function without looping.
x = 'hu1_X','hu2_Y','hu3_H','hu4_H','hu5_H','hu7_H'
y = 'hu1_H','hu2_X','hu3_H','hu4_H','hu5_H','hu7_X'
for comparing the above string the final match count is 3.
Matches are: 'hu3_H','hu4_H','hu5_H'.
Any idea, which in-built function can use? Can we go with ZIP() in Python.
Thanks in advance.
You can use a generator expression and the builtin sum function along with zip, like this
x = 'hu1_X', 'hu2_Y', 'hu3_H', 'hu4_H', 'hu5_H', 'hu7_H'
y = 'hu1_H', 'hu2_X', 'hu3_H', 'hu4_H', 'hu5_H', 'hu7_X'
print(sum(item1 == item2 for item1, item2 in zip(x, y)))
# 3
This works because, in Python, True and False can be treated as 1 and 0 respectively. So, we can simply compare the corresponding elements and the result of that evaluation can be added together to get the total match count.

In python is there a data structure that can use duplicate strings as index? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In the following code snippet for text summary, it is intended to store an integer/importance value corresponding to each sentence in a paragraph.I tried using dictionary , but have issues with similar indices Is there a data structure in python that can make use of a string as an index where single string may occur multiple times?
line = fr.readline()
relevance = {}
while line:
line_value = select(line)
relevance[line] = line_value #error in this line
line = fr.readline()
The best data structure depends on what you then need to do with it.
A dictionary might work. However:
standard dictionaries are unordered
duplicate strings might need special handling.
If neither is a problem, simply change [] to {} in your code.
Another alternative is to have a list of (line,value) tuples. This will preserve the ordering of data and duplicates, but will not offer efficient string-based lookups.

Assuming that s is a string of lower case characters. how would i find the number of string y inside s [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
the following problem in python please .....
Assuming that s is a string of lower case characters.
how would I write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then my program would print
'Number of times bob occurs is: 2'
I am a completely new to python and appreciate any help
If you didn't want to count overlapping bobs as separate values, this would be easy:
s.count('bob')
But you apparently do. (I had to guess that, based on the fact that your intended output is 2 rather than 1… in the future, it would be better to explain your problem instead of leaving it ambiguous.) As the help says, count returns "the number of non-overlapping occurrences of substring sub…", so that won't do any good.
So, for that, you will have to do it manually. I'll show an example that should have enough to get you started:
for i in range(len(s)):
if s[i:].startswith('bob'):
print('Found a bob')
A slightly smarter way to do this would be to use the find method on strings. You can find details on this in the online docs, or by typing help(str.find) in the interactive console. Notice that find takes a start argument. You should be able to figure out how this would help you; it may take a bit of work to get the details right, but if you get stuck, you can always post a new question asking for specific help.
You can try this way
string = "BOBOBOBOBOABCDE"
search = "BOB"
print len([i for i in range(len(string)) if string.startswith(search, i)])

Python convert email [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am writing a small program that reads in email and outputs only part of it.
Example
someone.lastname#example.com
I want the output to be someonel
so in this case i want the first part of the email before the "." and then the first letter of the second part in this case "l"
I need some assistance on how to concatenate these 2 parts taking only one character from the second part after the "."
thank you in advance
One way:
>>> first, rest = 'someone.lastname#example.com'.split('.', 1)
>>> first + rest[:1]
'someonel'
You should find the index of the first occurrence of dot and then use this index to split the string.
st = 'someone.lastname#example.com'
dot_index = st.index('.')
new_st = st.rjust(st[dot_index + 2])
This returns an array for new_st that its first element is what you want.
I used +2, because the argument is the length, so we should +1 the index and the second +1 is for counting the next character after the dot.

IndexError: string index out of range(str1[-1]) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Here is my function:
def find_last(str1):
return str1[-1]
When i run it:
print find_last('aaaa')
I have the following error:
return str1[-1]
IndexError: string index out of range
How can I fix this?
Thanks.
The function as you have written it fails only if an empty string is passed in (or something that's not a string or other sequence, of course). A great way to make sure this works without having to check for the empty string is to use slicing rather than indexing:
def get_last(text):
return text[-1:]
This means "return from the last character through the end." This works even on empty strings because slicing stops at either end of the string automatically.
Your code is fine:
>>> def find_last(str1):
... return str1[-1]
...
>>> print find_last('aaaa')
a
>>>
You shouldn't get that response with 'aaaa' but you could improve your function with:
def find_last(str1):
return str1[-1] if str1 else None

Categories