Python Django- Not Returning a Valid Result - python

I am generating all possible combinations for the given scrambled letters and storing it in a list. Then, I'm checking if words from that list are in my database. Although, the word is in the database, it is not returning so.
example for result list:
result = ['aargh', 'raagh', 'hraag']
Although there is a word called aargh in my database, its not returning it.
for r in result:
# print(r)
try:
actual = Dictionary.objects.get(word=r)
print(actual.word)
except:
actual = 'Not found'
print("Actual Word " + str(actual))
I have words stored in 'Dictionary' Table. What is wrong here?

you can check wheter the word exists or not:
for r in result:
actual = Dictionary.objects.filter(word__iexact=r).first()
if actual:
print(actual.word)
actual = actual.word
else:
actual = 'Not found'
print("Actual Word " + str(actual))

Try using icontains
Ex:
actual = Dictionary.objects.get(word__icontains=r)
Info on icontains

Related

How do I check whether an input string has alphabets in another string in Python?

As the title says, how do I check whether an input string has alphabets in another string in Python?
The string specifies that only alphabets A to G ('ABCDEFG') can be used in the input string. However, my attempt did not get the results I want. Instead, input strings with alphabets in order such as 'ABC' and 'ABCD' work, while those not in order such as 'BADD' and 'EFEG' do not.
Please refer to my attempt below.
ID = 'ABCDEFG'
addcode=input('Enter new product code: ')
Code = []
if addcode in ID:
Code.append(addcode)
print(Code)
else:
print("Product code is invalid")
Ideally, as long as the input string contain letters from A to G, it should be appended to 'Code' regardless of the order. How do I modify my code so that I can get the results I want? Thank you.
You can use RegEx:
re.search('[a-zA-Z]', string)
You can try converting your input string (addcode) to a set and then see if it is a subset of ID. I am not converting ID into a set as it contains unique elements as per your code:
ID = 'ABCDEFG'
addcode = input('Enter new product code: ')
Code = []
if set(addcode).issubset(ID):
Code.append(addcode)
print(Code)
else:
print("Product code is invalid")
If you want to use a RegEx based approach, you can do this:
import re
pattern = re.compile("^[A-G]+$")
addcode = input('Enter new product code: ')
Code = []
if pattern.findall(addcode):
Code.append(addcode)
print(Code)
else:
print("Product code is invalid")
We are checking if the input string contains only characters between A-G here i.e A,B,C,D,E,F,G. If there is a match, we append the input string and print it.
String is immutable. You should check whether each letter of product code is present in the ID.
To achieve this you can use ID as tuple instead of single string.
ID = ('A','B','C','D','E','F','G')
addcode=input('Enter new product code: ')
Code = []
for l in range(0,len(addcode)):
if addcode[l] in ID:
Code.append(addcode[l])
else:
print("Product code is invalid")
print(Code)

Why Does This Return None when entering a list[0]?

'zipcodes.txt' is a text file with just zipcodes. The script works correct if I just enter a zipcode e.g. "90210". zip_list[0] type is a string and when printed it returns a single zipcode. However with the code as is a keep getting 'None'
from uszipcode import SearchEngine
search = SearchEngine(simple_zipcode=False)
zip_list = list(open("zipcodes.txt","r"))
search_by_zip = search.by_zipcode(zip_list[0])
print(search_by_zip.major_city)
I changed the variable names around a bit to make sense for me, but I had to strip() the list to get rid of the '\n'
first_list = list(open("zipcodes.txt","r"))
zip_list = []
for item in first_list:
zip_list.append(item.strip())

Google search from Python program

I'm trying to take an input file, read each line, search google with that line and print all the search results from the query ONLY IF the result is from a specific website. A simple example to illustrate my point, if I search dog I only want results printed from wikipedia, whether that be one result or ten results from wikipedia. My problem is I've been getting really weird results. Below is my Python code which contains a specific URL I want results from.
My program
inputFile = open("small.txt", 'r') # Makes File object
outputFile = open("results1.txt", "w")
dictionary = {} # Our "hash table"
compare = "www.someurl.com/" # urls will compare against this string
from googlesearch import GoogleSearch
for line in inputFile.read().splitlines():
lineToRead = line
dictionary[lineToRead] = [] #initialzed to empty list
gs = GoogleSearch(lineToRead)
for url in gs.top_urls():
print url # check to make sure this is printing URLs
compare2 = url
if compare in compare2: #compare the two URLs, if they match
dictionary[lineToRead].append(url) #write out query string to dictionary key & append EACH url that matches
inputFile.close()
for i in dictionary:
print i # this print is a test that shows what the query was in google (dictionary key)
outputFile.write(i+"\n")
for j in dictionary[i]:
print j # this print is a test that shows the results from the query which should look like correct URL: "www.medicaldepartmentstore.com/..."(dictionary value(s))
outputFile.write(j+"\n") #write results for the query string to the output file.
My output file is incorrect, the way it's supposed to be formatted is
query string
http://www.
http://www.
http://www.
query string
http://www.
query string
http://www.medical...
http://www.medical...
Can you limit the scope of the results to the specific site (e.g. wikipedia) at the time of the query? For example, using:
gs = GoogleSearch("site:wikipedia.com %s" % query) #as shown in https://pypi.python.org/pypi/googlesearch/0.7.0
This would instruct Google to return only the results from that domain, so you won't need to filter them after seeing the results.
I think #Cahit has the right idea. The only reason you would be getting lines of just the query string is because the domain you were looking for wasn't in the top_urls(). You can verify this by checking if the array contained in the dictionary for a given key is empty
for i in dictionary:
outputFile.write("%s: " % str(i))
if len(dictionary[i]) == 0:
outputFile.write("No results in top_urls\n")
else:
outputFile.write("%s\n" % ", ".join(dictionary[i]))

If not found assign value

I am pulling data out of a file that looks like this
"LIC_ARP11|104100000X|33"
I collect the taxonomy number (taxonomies) out of the second field and translate it using another file (IDVtaxo) that looks like this:
"104100000X Behavioral Health & Social Service Providers Social Worker"
If the taxonomy number is not in IDVtaxo I want to append "Not Found"
if taxofile.startswith('IDV'):
for nums in taxonomies:
IDVfile = open (os.path.join(taxodir,IDVtaxo))
for line in IDVfile:
text = line.rstrip('\n')
text = text.split("\t")
if nums in line:
data = text[2:]
final.append(data)
else:
final.append('Not Found')
Then I print the original data along with the translated taxonomy. Currently I get:
"LIC_ARP11|104100000X|33| Not Found"
I want:
"LIC_ARP11|104100000X|33 | Social Worker"
The issue seems to be that the "else" appends "Not Found" for each line instead of just when the taxonomy isn't found in IDVtaxo.
taxonomies = ['152W00000X', '156FX1800X', '200000000X', '261QD0000X', '3336C0003X', '333600000X', '261QD0000X']
translations = {'261QD0000X': 'Clinic/Center Dental', '3336C0003X': 'Pharmacy Community/Retail Pharmacy', '333600000X': 'Pharmacy'}
a = 0
final = []
for nums in taxonomies:
final.append(translations.get(nums, 'Not Found'))
for nums in taxonomies:
print nums, "|", final[a]
a = a + 1
equality operator in Python is ==:
>>> if data == 'Not Found':
... final.append(data)
for "not equal":
>>> if data != 'Not Found':
... final.append(data)
It appears you are testing for presence of nums in each line, appending 'Not Found' every time you fail to find nums.
Instead, try maintaining a variable (e.g. job_title) storing 'Not Found' string. If nums is found, reassign job_title to correct value and append it to final outside of the loop.
I believe you can get a more efficient solution if you load IDVtaxo into a dictionary structure! https://docs.python.org/2/tutorial/datastructures.html#dictionaries

Python - How to print a specific text

def handler_users_answ(coze, res, type, source):
if res:
if res.getType() == 'result':
aa=res.getQueryChildren()
if aa:
print 'workz1'
for x in aa:
m=x.getAttr('jid')
if m:
print m
so this code returns me the values like this:
roomname#domain.com/nickname1
roomname#domain.com/nickname2
and so on, but i want it to print the value after the '/' only.
like:
nickname1
nickname2
Thanks in advance.
You can use rpartition to get the part after the last \ in the string.
a = 'roomname#domain.com/nickname1'
b=a.split('/');
c=b[1];
You can use rsplit which will do the splitting form the right:
a = 'roomname#domain.com/nickname1'
try:
print a.rsplit('/')[1][1]
except IndexError:
print "No username was found"
I think that this is efficient and readable. If you really need it to be fast you can use rfind:
a = 'roomname#domain.com/nickname1'
index = a.rfind('/')
if index != -1:
print a[index+1:]
else:
print "No username was found"
To fully parse and validate the JID correctly, see this answer. There's a bunch of odd little edge cases that you might not expect.

Categories