Related
This question already has answers here:
What is a 'NoneType' object?
(13 answers)
Closed 1 year ago.
I have been making a morse code translator and I have just arrived at a problem with translating from morse.
Here is my code:
def translate(self, message):
message_words = message.split(' ')
message_in_morse = ['Your message is: ']
letters = {'.-':'a', '-...':'b', '-.-.':'c', '-..':'d', '.':'e', '..-.':'f', '--.':'g', '....':'h', '..':'i', '.---':'j', '-.-':'k', '.-..':'l', '--':'m', '-.':'n', '---':'o', '.--.':'p', '--.-':'q', '.-.':'r', '...':'s', '-':'t', '..-':'u', '...-':'v', '.--':'w', '-..-':'x', '-.--':'y', '--..':'z', '.----':'1', '..---':'2', '...--':'3', '....-':'4', '.....':'5', '-....':'6', '--...':'7', '---..':'8', '----.':'9', '-----':'0', '..--..':'?', '.-.-.-':'.', '--..--':',', ' ':' ', ' ':''}
morse_text = ''
for letter in message_words:
message_in_morse.append(letters.get(letter.lower()))
message_in_morse.append(' ')
try:
morse_text = ''.join(message_in_morse)
except Exception as e:
print('Error: ', str(e))
return morse_text
I am importing it and running translate('.- .-')
from another program.
This should output:
Your message is: aa
When I run this, it just says:
Error: sequence item 1: expected str instance, NoneType found
I don't know what this means or how to fix it.
Your try/except confused me for a while.
Still, I managed to find your typo:
def translate(self, message):
message_words = message.split(' ') # split by one space
message_in_morse = ['Your message is: ']
letters = {'.-':'a', '-...':'b', '-.-.':'c', '-..':'d', '.':'e', '..-.':'f', '--.':'g', '....':'h', '..':'i', '.---':'j', '-.-':'k', '.-..':'l', '--':'m', '-.':'n', '---':'o', '.--.':'p', '--.-':'q', '.-.':'r', '...':'s', '-':'t', '..-':'u', '...-':'v', '.--':'w', '-..-':'x', '-.--':'y', '--..':'z', '.----':'1', '..---':'2', '...--':'3', '....-':'4', '.....':'5', '-....':'6', '--...':'7', '---..':'8', '----.':'9', '-----':'0', '..--..':'?', '.-.-.-':'.', '--..--':',', ' ':' ', ' ':''}
morse_text = ''
for letter in message_words:
message_in_morse.append(letters.get(letter.lower()))
try:
morse_text = ''.join(message_in_morse)
except Exception as e:
print('Error: ', str(e))
return morse_text
print(translate('.- .-'))
Output:
Your message is: aa
Also, you should try to allow for invalid morse:
message_in_morse.append(letters.get(letter.lower(), '#'))
This will give # for any unknown morse code.
Update: removed the extra space between decoded characters.
I've discovered how to get it to work.
Use nested for loops to split the message into words, then each word gets split into separate letters.
message_words = message.split(' ')
letters_in_message = []
for word in message_words:
letters_in_message.append(word.split(' '))
message_in_morse = ['Your message: ']
letters = {'.-':'a', '-...':'b', '-.-.':'c', '-..':'d', '.':'e', '..-.':'f', '--.':'g', '....':'h', '..':'i', '.---':'j', '-.-':'k', '.-..':'l', '--':'m', '-.':'n', '---':'o', '.--.':'p', '--.-':'q', '.-.':'r', '...':'s', '-':'t', '..-':'u', '...-':'v', '.--':'w', '-..-':'x', '-.--':'y', '--..':'z', '.----':'1', '..---':'2', '...--':'3', '....-':'4', '.....':'5', '-....':'6', '--...':'7', '---..':'8', '----.':'9', '-----':'0', '..--..':'?', '.-.-.-':'.', '--..--':',', ' ':' ', ';':' '}
morse_text = ''
for word in letters_in_message:
for letter in word:
message_in_morse.append(letters.get(letter.lower(), '#'))
message_in_morse.append(' ')
morse_text = ''.join(message_in_morse)
return morse_text
Code to extract sequences
from Bio import SeqIO
def get_cds_feature_with_qualifier_value(seq_record, name, value):
for feature in genome_record.features:
if feature.type == "CDS" and value in feature.qualifiers.get(name, []):
return feature
return None
genome_record = SeqIO.read("470.8208.gbk", "genbank")
db_xref = ['fig|470.8208.peg.2198', 'fig|470.8208.peg.2200', 'fig|470.8208.peg.2203', 'fig|470.8208.peg.2199', 'fig|470.8208.peg.2201', 'fig|470.8208.peg.2197', 'fig|470.8208.peg.2202', 'fig|470.8208.peg.2501', 'fig|470.8208.peg.2643', 'fig|470.8208.peg.2193', 'fig|470.8208.peg.2670', 'fig|470.8208.peg.2695', 'fig|470.8208.peg.2696', 'fig|470.8208.peg.2189', 'fig|470.8208.peg.2458', 'fig|470.8208.peg.2191', 'fig|470.8208.peg.2190', 'fig|470.8208.peg.2188', 'fig|470.8208.peg.2192', 'fig|470.8208.peg.2639', 'fig|470.8208.peg.3215', 'fig|470.8208.peg.2633', 'fig|470.8208.peg.2682', 'fig|470.8208.peg.3186', 'fig|470.8208.peg.2632', 'fig|470.8208.peg.2683', 'fig|470.8208.peg.3187', 'fig|470.8208.peg.2764', 'fig|470.8208.peg.2686', 'fig|470.8208.peg.2638', 'fig|470.8208.peg.2680', 'fig|470.8208.peg.2685', 'fig|470.8208.peg.2684', 'fig|470.8208.peg.2633', 'fig|470.8208.peg.2682', 'fig|470.8208.peg.3186', 'fig|470.8208.peg.2632', 'fig|470.8208.peg.2683', 'fig|470.8208.peg.3187', 'fig|470.8208.peg.2640', 'fig|470.8208.peg.3221', 'fig|470.8208.peg.3222', 'fig|470.8208.peg.3389', 'fig|470.8208.peg.2764', 'fig|470.8208.peg.2653', 'fig|470.8208.peg.3216', 'fig|470.8208.peg.3231', 'fig|470.8208.peg.2641', 'fig|470.8208.peg.2638', 'fig|470.8208.peg.2680', 'fig|470.8208.peg.2637', 'fig|470.8208.peg.2642', 'fig|470.8208.peg.2679', 'fig|470.8208.peg.3230', 'fig|470.8208.peg.2676', 'fig|470.8208.peg.2677', 'fig|470.8208.peg.1238', 'fig|470.8208.peg.2478', 'fig|470.8208.peg.2639', 'fig|470.8208.peg.854', 'fig|470.8208.peg.382', 'fig|470.8208.peg.383']
with open("nucleotides.fasta", "w") as nt_output, open("proteins.fasta", "w") as aa_output:
for xref in db_xref:
print ("Looking at " + xref)
cds_feature = get_cds_feature_with_qualifier_value (genome_record, "db_xref", xref)
gene_sequence = cds_feature.extract(genome_record.seq)
protein_sequence = gene_sequence.translate(table=11, cds=True)
# This is asking Python to halt if the translation does not match:
assert protein_sequence == cds_feature.qualifiers["translation"][0]
# Output FASTA records - note \n means insert a new line.
# This is a little lazy as it won't line wrap the sequence:
nt_output.write(">%s\n%s\n" % (xref, gene_sequence))
aa_output.write(">%s\n%s\n" % (xref, gene_sequence))
print("Done")
getting following error
/usr/local/lib/python3.7/dist-packages/Bio/GenBank/Scanner.py:1394: BiopythonParserWarning: Truncated LOCUS line found - is this correct?
:'LOCUS CP027704 3430798 bp DNA linear UNK \n'
BiopythonParserWarning,
Looking at fig|470.8208.peg.2198
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-32-323ff320990a> in <module>()
15 print ("Looking at " + xref)
16 cds_feature = get_cds_feature_with_qualifier_value (genome_record, "db_xref", xref)
---> 17 gene_sequence = cds_feature.extract(genome_record.seq)
18 protein_sequence = gene_sequence.translate(table=11, cds=True)
19
AttributeError: 'NoneType' object has no attribute 'extract'
You have a space between the get_cds_feature_with_qualifier_value call and its parameters (genome_record, "db_xref", xref), so the call is probably failing, leaving cds_feature as None.
Generally, you should provide reproducible examples so that someone else (who doesn't have the gbk file you're referencing) can still reproduce and troubleshoot your error.
Solved the problem.
'''
from Bio import SeqIO
def get_cds_feature_with_qualifier_value(seq_record, name, value):
for feature in genome_record.features:
if feature.type == "CDS" and value in feature.qualifiers.get(name, []):
return feature
return None
genome_record = SeqIO.read("470.8208.gbk", "genbank")
da_xref = ['fig|470.8208.peg.2198', 'fig|470.8208.peg.2200', 'fig|470.8208.peg.2203', 'fig|470.8208.peg.2199', 'fig|470.8208.peg.2201', 'fig|470.8208.peg.2197', 'fig|470.8208.peg.2202', 'fig|470.8208.peg.2501', 'fig|470.8208.peg.2643', 'fig|470.8208.peg.2193', 'fig|470.8208.peg.2670', 'fig|470.8208.peg.2695', 'fig|470.8208.peg.2696', 'fig|470.8208.peg.2189', 'fig|470.8208.peg.2458', 'fig|470.8208.peg.2191', 'fig|470.8208.peg.2190', 'fig|470.8208.peg.2188', 'fig|470.8208.peg.2192', 'fig|470.8208.peg.2639', 'fig|470.8208.peg.3215', 'fig|470.8208.peg.2633', 'fig|470.8208.peg.2682', 'fig|470.8208.peg.3186', 'fig|470.8208.peg.2632', 'fig|470.8208.peg.2683', 'fig|470.8208.peg.3187', 'fig|470.8208.peg.2764', 'fig|470.8208.peg.2686', 'fig|470.8208.peg.2638', 'fig|470.8208.peg.2680', 'fig|470.8208.peg.2685', 'fig|470.8208.peg.2684', 'fig|470.8208.peg.2633', 'fig|470.8208.peg.2682', 'fig|470.8208.peg.3186', 'fig|470.8208.peg.2632', 'fig|470.8208.peg.2683', 'fig|470.8208.peg.3187', 'fig|470.8208.peg.2640', 'fig|470.8208.peg.3221', 'fig|470.8208.peg.3222', 'fig|470.8208.peg.3389', 'fig|470.8208.peg.2764', 'fig|470.8208.peg.2653', 'fig|470.8208.peg.3216', 'fig|470.8208.peg.3231', 'fig|470.8208.peg.2641', 'fig|470.8208.peg.2638', 'fig|470.8208.peg.2680', 'fig|470.8208.peg.2637', 'fig|470.8208.peg.2642', 'fig|470.8208.peg.2679', 'fig|470.8208.peg.3230', 'fig|470.8208.peg.2676', 'fig|470.8208.peg.2677', 'fig|470.8208.peg.1238', 'fig|470.8208.peg.2478', 'fig|470.8208.peg.2639', 'fig|470.8208.peg.854', 'fig|470.8208.peg.382', 'fig|470.8208.peg.383']
db_xref=[]
for xref in da_xref:
db_xref.append('SEED:' + xref)
with open("nucleotides.fasta", "w") as nt_output, open("proteins.fasta", "w") as aa_output:
for xref in db_xref:
print ("Looking at", xref)
cds_feature = get_cds_feature_with_qualifier_value(genome_record, "db_xref", xref)
gene_sequence = cds_feature.extract(genome_record.seq)
protein_sequence = gene_sequence.translate(table=11, cds=True)
# This is asking Python to halt if the translation does not match:
assert protein_sequence == cds_feature.qualifiers["translation"][0]
# Output FASTA records - note \n means insert a new line.
# This is a little lazy as it won't line wrap the sequence:
nt_output.write(">%s\n%s\n" % (xref, gene_sequence))
aa_output.write(">%s\n%s\n" % (xref, gene_sequence))
print("Done")
'''
I'm trying to set a property with a value which could have with space.I'm using py2neo and I wrote this, but it doesn't work:
name = mention['name']
screen_name = mention['screen_name']
id = mention['id']
graph.run(
'MATCH (f) '
'WHERE EXISTS(f.account_id) AND f.account_id=\'' + id + '\' '
'SET f.name=\'' + re.escape(name) + '\', f.screen_name=\'#' + screen_name + '\' '
'RETURN null'
)
How can I solve ? Thanks
You should pass the values (including the problematic value for name) as parameters. That avoids messy issues with the Python and Cypher parsers (and escaping the string value should also not be necessary).
This may work for you:
graph.run(
'MATCH (f) '
'WHERE f.account_id=$id '
'SET f.name=$name, f.screen_name=$screen_name',
{"id": mention['id'], "name": mention['name'], "screen_name": '#'+mention['screen_name']}
)
P.S: I assume you are trying to set the property screen_name with
space.
You placed space after \' (single quote), It should be before it:
graph.run(
'MATCH (f) '
'WHERE EXISTS(f.account_id) AND f.account_id=\'' + id + '\''
'SET f.name=\'' + re.escape(name) + '\', f.screen_name=\'#' + screen_name + ' \''
'RETURN null'
)
I am getting the following error code in Python when I am trying to run a loop through a directory.
File "C:/Users/mikes/Anaconda3/Lib/site-packages/spyder/utils/site/untitled1.py", line 17, in <module>
for country in rivers.values():
AttributeError: 'str' object has no attribute 'values'
This is my code:
rivers = {'nile' : 'egypt', 'ohio' : 'us', 'rhine' : 'germany' }
# prints river name
for rivers in rivers.keys():
print (rivers)
# prints country
for country in rivers.values():
print (river)
# prints statement " The (river) is in the country of (country)
for rivers in rivers:
print ("The " + rivers.keys() + "is in the country of " + rivers.vaules())
In the statement for rivers in rivers.keys():, you redefine rivers: at the end of the loop, it becomes the name of the last key (a string) and does not refer to the dictionary anymore. Solution: use another name for the loop variable.
You have a few things wrong with your code. Your country loop uses the wrong variable name, you redefine rivers (which is what gives you your error), and your print statement won't work anyway
rivers = {'nile' : 'egypt', 'ohio' : 'us', 'rhine' : 'germany' }
# prints river name
for river in rivers.keys():
print (river)
# prints country
for country in rivers.values():
print (country)
# prints statement " The (river) is in the country of (country)
for river in rivers:
print ("The " + river + "is in the country of " + rivers[river])
I am trying to iterate through a yaml file. I want to extract the contents
ipv6: "2031:31:31:31:: 2032:32:32:32:: 2033:33:33:33:: 2034:34:34:34:: 2035:35:35:35::"
Below is my code. I get the below error :
for x in self.dhcp_dict['subnets'][sub]['ipv4'].split():
TypeError: string indices must be integers, not str
Can anyone tell em where i am going wrong? Thanks
Jessi
Code:
dict = yaml.load(fd)
self.server_dict = dict['server_configs']
self.interface_dict = self.server_dict['interface']
self.dhcp_dict = self.server_dict['dhcp_config']
def configureDhcpv6(self):
pdb.set_trace()
log.info ("Writing the dhcp.conf file")
infile = open('v6.txt', 'w+')
self.lease_time = self.dhcp_dict['lease_time']
infile.write("default-lease-time %s; \n" %(self.lease_time))
infile.write("preferred-lifetime 604800;\noption dhcp-renewal-time 604800;\noption dhcp-rebinding-time 7200;\noption dhcp6.domain-search cisco.com;\noption dhcp6.preference 255;\noption dhcp6.rapid-commit;\noption dhcp6.info-refresh-time 21600;\ndhcpv6-lease-file-name /var/lib/dhcpd/dhcpd6.leases;\nauthoritative;\nlog-facility local7;\n\n")
for sub in self.dhcp_dict['subnets']:
if (sub == 'relay'):
for x in self.dhcp_dict['subnets'][sub]['ipv6'].split():
range6 = sub + "11" + " " + sub + "254"
infile.write("Subnet 6 %s/64 {\n" % (sub))
infile.write(" range6 %s;\n}\n\n" % (range6))
infile.close()
Yaml file:
dhcp_config:
lease_time: "300"
relay_server: "5.5.5.0"
subnets:
relay:
ipv4: "30.30.30.0 31.31.31.0 32.32.32.0 33.33.33.0 34.34.34.0 35.35.35.0"
ipv6: "2031:31:31:31:: 2032:32:32:32:: 2033:33:33:33:: 2034:34:34:34:: 2035:35:35:35::"
smart_relay: "31.1.1.0 32.1.1.0 33.1.1.0 34.1.1.0 35.1.1.0"
snoop: "36.36.36.0 37.37.37.0 38.38.38.0 39.39.39.0 30.30.30.0"