pymongo no output for query - python

EDIT:
I have somewhat distilled the question.
mongo_documents = mongo_collection.find({"medicalObjectId": "269"})
print "\n\n"
for this_document in mongo_documents:
print this_document
print "-------------------------"
pqr = 269
mongo_documents2 = mongo_collection.find({"medicalObjectId": pqr})
print "\n\n"
for this_document2 in mongo_documents2:
print this_document2
My problem is that the first code chunk where I use the number as the key in the query, works. But the second chunk where I use the variable, i get no output.
I am a beginner at python and pymongo, so please bear with me.
I have a list as;
row = [1, 2, ...., 100]
I want to query a mongodb collection for each entry in my list.
The collection has the format:
collection = {'pk', 'attribute1', 'attribute2', 'attribute3'}
I want to call the mongodb connection and iterate through each entry in my list with row[i]=pk and return the other attributes as the output.
ie. mongo_documents = mongo_collection.find({'pk' : row[0]})
mongo_documents = mongo_collection.find({'pk' : row[1]})
and so on.
The code that I have is:
for row in result_set:
print row[0]
mongo_documents = mongo_collection.find({'medicalObjectId' : row[0]})
print mongo_documents
for this_document in mongo_documents:
print "----------------------------------"
print this_document
however i get no output. where am I going wrong?
if i print mongo_documents, i get
<pymongo.cursor.Cursor object at 0xe43150>

You could use the $in operator of mongodb to fetch all the rows at once and iterate through them.
mongo_documents = mongo_collection.find({ 'medicalObjectId' : { '$in' : result_set } } );
for doc in mongo_documents:
print mongo_documents
I have not tested it, comment below if it doesnt work.
EDIT
mongo_documents2 = mongo_collection.find({"medicalObjectId": str(pqr)})
print "\n\n"
for this_document2 in mongo_documents2:
print this_document2

Related

Python Django- Not Returning a Valid Result

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

Use IF statement to search json file

I need to search this json file and print only the peole with a Y status:
[[{"Name": "person1", "Status": "Y"}], [{"Name": "person2", "Status": "N"}], [{"Name": "person3", "Status": "Y"}]]
I can open the file and display the data ok, but need to search within it.
Could someone help complete this if statement for me?
It needs to look at the keyvalue? Status and print only the two people with Y
for name in OpenFile:
**# if Status == Y what do I do here? :**
print ("Name : " +name[i]['Name'])
print ("Status : " +name[i]['Status'])
You need to iterate over the lists, extract the dict from it and check the key 'Status':
for element in OpenFile:
ele = element[0] # grab the dict
if ele.get('Status') == 'Y':
print 'Name: {}'.format(ele.get('Name')
print 'Status: {}'.format(ele.get('Status')
Your OpenFile object is a list of lists, which inside it's dict structure.
So, you want to address the first object in your list (that's the dict) and then perform your check. You do that with ele.get()
It looks like you are referencing [i], while name is your iterator. Change it to something like this:
for name in OpenFile:
**# if Status == Y what do I do here? :**
print ("Name : " +name['Name'])
print ("Status : " +name['Status'])
at the same time, your json formatted data looks like it's formatted like this:
List[list[dict],list[dict],list[dict],] so it'd only make sense to navigate to the Name value like this:
print(OpenFile[0][0]['Name'])
Try if this returns person1 and then base your next if-statement on this.
Additional debugging tool:
use type() to identify how your json is formatted:
type(OpenFile)
type(OpenFile[0])
type(OpenFile[0][0])
etc., use the error to figure out how your json is formatted

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]))

Twitter Trending List Printing First Character Instead of First Entry

I'm having an issue where I can get the Twitter API to provide me with the top 10 list of trending topics in a given area, but I can only get the entirety to print, or the first character to print, but not the first entry in the list.
The following code is what I tried to just print the first entry in the list (entry 0) but I get the first character for each list entry instead (character 0).
from twitter import *
access_token = "myaccesstoken"
access_token_secret = "myaccesstokensecret"
consumer_key = "consumerkey"
consumer_secret = "consumersecret"
t = Twitter(auth=OAuth(access_token, access_token_secret, consumer_key, consumer_secret))
results = t.trends.place(_id = 2442047)
#I used the Los Angeles WOEID
for location in results:
for trend in location["trends"]:
trendlist = trend["name"]
print trendlist[0]
If I just use a simple list like this, I can get Python to just print the first entry:
trendlist = ['one', 'two', 'three']
print trendlist[0]
Can anyone provide a pointer on why this behavior is different and how to just get one entry to print from the Trending list?
Thank you!
The trends api returns something like this:
"trends": [
{
"events": null,
"name": "#GanaPuntosSi",
"promoted_content": null,
"query": "%23GanaPuntosSi",
"url": "http://twitter.com/search/?q=%23GanaPuntosSi"
}...]
With your second for loop you iterate through each of the above trend "objects".
trendlist = trend["name"]
doesn't get you a list, but the trend name.
print trendlist[0]
prints out the first letter of the name.
Just print trend["name"] and you are done.
Here's a little repl.it for you https://repl.it/BLww/1. You are printing all 10 because you are looping through them all. If you want to print just the first one, you can do this:
for location in results:
print location["trends"][0]['name']

Python: Formatting lists of lists

I'm a newbie to Python. I have the code below which basically extracts some 5 rows from a MySql table.
if keyword.lower() == 'last5':
cursor.execute('SELECT income_Ref, income_Amount FROM model_income WHERE company_MobileNumber = %s ORDER BY income_Datetime DESC LIMIT 5', [sender])
result = cursor.fetchall()
result = [list(row) for row in result]
self.respond(result)
return ()
The self.respond() kinda works like print() but it sends a text message instead.I am having trouble formatting the output. What I get from the code above is a list of lists which looks likes this:
[[u'2014-11-06fd753b-inc', u'50.0'], [u'2014-11-067d724b-inc', u'50.0'], [u'2014-11-067557d6-inc', u'50.0']]
I really wish I new how to make it look like this:
Ref:2014-11-06fd753b-inc Amount:50.0
Ref:2014-11-067d724b-inc Amount:50.0
Ref:2014-11-067557d6-inc Amount:50.0
That includes prefixing 'Ref' and 'Amount' before each respective field. I swear I have searched high and low on how to do that for a week now but I'm failing to crack it.
You can use:
self.respond("\n".join("Ref:{} Amount:{}".format(ref, amt) for ref, amt in result))
Not really beginner material, but...
Joining a string (created by formatting "Ref:{} Amount:{}") with "\n" using a generator
if keyword.lower() == 'last5':
cursor.execute('SELECT income_Ref, income_Amount FROM model_income WHERE company_MobileNumber = %s ORDER BY income_Datetime DESC LIMIT 5', [sender])
result = cursor.fetchall()
result = [list(row) for row in result]
self.respond("\n".join("Ref:{} Amount:{}".format(ref, amt) for ref, amt in result))
return ()
I left the list comprehension result = [list(row) for row in result] because I don't know what fetchall() actually returns.
Output:
Ref:2014-11-06fd753b-inc Amount:50.0
Ref:2014-11-067d724b-inc Amount:50.0
Ref:2014-11-067557d6-inc Amount:50.0
["Ref:" + i[0][2:-1] + " Amount: " + i[1][2:-1] + "\n" for i in result]

Categories