trying to get a wordlist from a textfile - python-3.x

Im testing new things and I landed on python... As first code i found the classic hangman game.
I followed a tutorial that shows how to do it step by step but when it comes to wordlist I've got lost...
So far I've been retrieving the words from a variable "_WORDS" which it has some strings as properties. I have now a "words.txt" file from which I want to get the words instead of the variable _WORDS = ("word1", "word2", "etc"). I found some examples but I cant hack it... some inspiration? This is my code...
_WORDS = open("words.txt", 'r')
_IFYOUWIN = ("you won!")
def __init__(self):
self._word = choice(self._WORDS)
self._so_far = "-" * len(self._word)
self._used = []
self._wrong_answers = 0
def play(self):
self._reset_game()
self._start_game()
while self._wrong_answers < len(self._HANGMAN) and self._so_far != self._word:
self._print_current_progress()
guess = self._user_guess()
self._check_answer(guess)
I tried importing "os" like this:
import os
_WORDS = os.path.expanduser("~/Desktop/pythontlearn/words.txt")
but no luck.

for the record I found this working for me
path = '/words.txt'
_WORDS = open(path,'r')
but Im still not sure why it does not work with something like
_WORDS = open("words.txt", 'r')
they look exactley the same to me

Related

Execute multiple Steps for entries in a List in Python

I try to load a list from a txt.file and then want to execute multiple task on every single entry. Unfortunately the tasks are executed only on one entry instead of all of them.
I load the list from the txt.file with this function:
def load_dir_file():
directory = os.path.dirname(__file__)
filename = os.path.join(directory, "law_dir")
with open(filename, "r", encoding="utf-8") as fin:
dir_file = fin.readlines()
return dir_file
This is the code to execute those tasks
def create_html():
dir_lst = load_dir_file()
for dir_link_dirty in dir_lst:
dir_link = dir_link_dirty.replace('"',"").replace(",","").replace("\n","")
dir_link_code = urllib.request.urlopen(dir_link)
bs_dir_link_code = BeautifulSoup(dir_link_code, "html5lib")
h2_a_tag = bs_dir_link_code.h2.a
html_link = str(dir_link) + "/" + str(h2_a_tag["href"])
print(dir_lst)
return html_link
The txt. file looks like this now:
"https://www.gesetze-im-internet.de/ao_1977",
"https://www.gesetze-im-internet.de/bbg_2009",
"https://www.gesetze-im-internet.de/bdsg_2018"
I am new to programming and probably fail some very basic points up there. So if you want to add some recommendation how i can improve basically, I would more then appreciate it.
Based on your comment above it sounds like you want to return a list of html links not just one. To do that you need that function to build a list and have it return that list. You have a lot going on in create_html, so for illustration purposes I split that function into two: create_html_link_list and create_html_link.
def create_html_link(dir_link_dirty):
dir_link = dir_link_dirty.replace('"',"").replace(",","").replace("\n","")
dir_link_code = urllib.request.urlopen(dir_link)
bs_dir_link_code = BeautifulSoup(dir_link_code, "html5lib")
h2_a_tag = bs_dir_link_code.h2.a
html_link = str(dir_link) + "/" + str(h2_a_tag["href"])
return html_link
def create_html_link_list():
dir_lst = load_dir_file()
html_link_list = [
create_html_link(dir_link_dirty)
for dir_link_dirty in dir_lst
]
return html_link_list

Why is this writing to a file incorrectly

Im writing some code for my schools sign in/out system and im kind of confused with the output im getting
In essence im checking each line of students which looks like 'name theircode' for each student and checkign it aganist the input code which all works
but when im printing in logged times it rewrites the previous line.
how do i fix this?
Here is the code
import time
lunch = str('inout {0}.txt'.format(time.strftime("%Y-%m-%d")))
while True:
variable = input()
with open ('students.txt') as f:
for eachline in f:
name,rfid = eachline.rsplit(None,1)
if variable == rfid:
print("yay")
with open('inout.txt','w+') as fp:
log = str('{0} loggged at {1}(ID: {2})'.format(name,time.strftime("%H:%M"),rfid))
fp.write('\n')
fp.write(log)
else:
print("nope")

Twitter API, Searching with dollar signs

This code opens a twitter listener, and the search terms are in the variable, upgrades_str. Some searches work, and some don't. I added AMZN to the upgrades list just to be sure there's a frequently used term since this is using an open Twitter stream, and not searching existing tweets.
Below, I think we only need to review numbers 2 and 4.
I'm using Python 3.5.2 :: Anaconda 4.0.0 (64-bit) on Windows 10.
Variable searches
Searching with: upgrades_str: ['AMZN', 'SWK', 'AIQUY', 'SFUN', 'DOOR'] = returns tweets such as 'i'm tired of people'
Searching with: upgrades_str: ['$AMZN', '$SWK', '$AIQUY', '$SFUN', '$DOOR'] = returns tweets as as 'Chicago to south Florida. Hiphop lives'. This search is the one I wish worked.
Explicit searches
Searching by replacing the variable 'upgrades_str' with the explicit string: ['AMZN', 'SWK', 'AIQUY', 'SFUN', 'DOOR'] = returns 'After being walked in on twice, I have finally figured out how to lock the door here in Sweden'. This one at least has the search term 'door'.
Searching by replacing the variable 'upgrades_str' with the explicit string: ['$AMZN', '$SWK', '$AIQUY', '$SFUN', '$DOOR'] = returns '$AMZN $WFM $KR $REG $KIM: Amazon’s Whole Foods buy puts shopping centers at risk as real'. So the explicit call works, but not the identical variable.
Explicitly searching for ['$AMZN'] = returns a good tweet: 'FANG setting up really good for next week! Added $googl jun23 970c avg at 4.36. $FB $AMZN'.
Explicitly searching for ['cool'] returns 'I can’t believe I got such a cool Pillow!'
import tweepy
import dataset
from textblob import TextBlob
from sqlalchemy.exc import ProgrammingError
import json
db = dataset.connect('sqlite:///tweets.db')
class StreamListener(tweepy.StreamListener):
def on_status(self, status):
if status.retweeted:
return
description = status.user.description
loc = status.user.location
text = status.text
coords = status.coordinates
geo = status.geo
name = status.user.screen_name
user_created = status.user.created_at
followers = status.user.followers_count
id_str = status.id_str
created = status.created_at
retweets = status.retweet_count
bg_color = status.user.profile_background_color
blob = TextBlob(text)
sent = blob.sentiment
if geo is not None:
geo = json.dumps(geo)
if coords is not None:
coords = json.dumps(coords)
table = db['tweets']
try:
table.insert(dict(
user_description=description,
user_location=loc,
coordinates=coords,
text=text,
geo=geo,
user_name=name,
user_created=user_created,
user_followers=followers,
id_str=id_str,
created=created,
retweet_count=retweets,
user_bg_color=bg_color,
polarity=sent.polarity,
subjectivity=sent.subjectivity,
))
except ProgrammingError as err:
print(err)
def on_error(self, status_code):
if status_code == 420:
return False
access_token = 'token'
access_token_secret = 'tokensecret'
consumer_key = 'consumerkey'
consumer_secret = 'consumersecret'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
stream_listener = StreamListener()
stream = tweepy.Stream(auth=api.auth, listener=stream_listener)
stream.filter(track=upgrades_str, languages=['en'])
Here's the answer, in case someone has the problem in the future: "Note that punctuation is not considered to be part of a #hashtag or #mention, so a track term containing punctuation will not match either #hashtags or #mentions." From: https://dev.twitter.com/streaming/overview/request-parameters#track
And for multiple terms, the string, which was converted from a list, needs to be changed to ['term1,term2']. Just strip out the apostrophes and spaces:
upgrades_str = re.sub('[\' \[\]]', '', upgrades_str)
upgrades_str = '[\''+format(upgrades_str)+'\']'

Import and run a file

I am a bit new to Python, and for some reason I can't get my head around something.
From the command line I run this
python3 myfile.py
And it works, at the bottom of the file is this, which runs my class, the bit that runs the class is show below (I have just included a bit of the section that calls the rest
if __name__ == "__main__":
dir = os.getcwd()
reportoutputpath="reports"
reportfilename=casedetails['hcname'] + ".html"
......
What I want to do, is run the complete file from my code, I tried this
pathforidefiles="/home/ubuntu/idefiles"
sys.path.append(pathforidefiles)
module = __import__("clean-Fern_Britton_Testcase_01")
This seems to read the file (I have a print line right at the top and that does seem to work, but nothing actually gets executed. I am sure I am missing something fundamental about the way Python works, but I am a bit lost.
Edit
I think I could be goint about this the wrong way, and think my question could be. How do I move what is in the main section of the file to me imported into the file that is doing the importing
The file to be imported is like this
class Examplecase01(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(30)
self.base_url = "http://example.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_fern_britton_testcase01(self):
driver = self.driver
....
if __name__ == "__main__":
dir = os.getcwd()
reportoutputpath="reports"
reportfilename=casedetails['hcname'] + ".html"
outfile = open(dir + "/" + reportoutputpath + "/" + reportfilename, "w")
loader = unittest.TestLoader()
suite = unittest.TestSuite((
loader.loadTestsFromTestCase(FernBrittonTestcase01)))
runner = HTMLTestRunner(stream=outfile,
verbosity=2,
title=casedetails['hcname'],
description=casedetails['hcdescription'])
t = unittest.main(exit=False)
print (t.result)
Then in the file that is doing the importing
mymodule=importlib.import_module('cleantest')
#code as above
t = unittest.mymodule(exit=False) #to replace t = unittest.main(exit=False)
The error I get is: module 'unittest' has no attribute 'mymodule'
So what do I need to do to make my code (that was in main) to work in my view that is doing the importing?
After some thought on what I actually wanted to do, this is what I came up with (It works). I am only really interested in running this from the site, not from the command line
loadfile="my-py-file-that-was-created-and-exported-from-the-IDE"
sys.path.append("directory-of-where-my-test-case-is")
mymodule=importlib.import_module(loadfile)
print(mymodule.casedetails['hcversion']) #I can access values in a dict on the imported file
#the below then gets the test case from the imported file
suite = unittest.TestSuite((loader.loadTestsFromTestCase(mymodule.Testcase01)))
In the view that does the work, as well as the above code, I also have most of the code that was in the main section of the original test case
I have other issues\questions, but this one is solved
Thanks
Grant

Using if elif statements with Tweepy in Python

I'm trying to create a bit of code to listen certain keywords on Twitter and am struggling to get the results I want.
I'm using Python 3.4.3.
Here's what I have that's working so far...
import tweepy
from time import sleep
CONSUMER_KEY = 'abcabcabc'
CONSUMER_SECRET = 'abcabcabc'
ACCESS_KEY = 'abcabcabc'
ACCESS_SECRET = 'abcabcabc'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
auth.secure = True
api = tweepy.API(auth)
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
try:
print(status.text)
except:
print("false")
myStreamListener = MyStreamListener
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener())
myStream.filter(track=['Cycling', 'Running'])
I'm trying to an if and elif statements to print different results depending on if the Tweet is Cycling or Running. I've used this code, but can't get it to work...
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
if 'Cycling' in myStreamListener:
print('Cyclist' + status.text)
elif 'Running' in myStreamListener:
print('Runner' + status.text)
else:
print('false' + status.text)
myStreamListener = MyStreamListener
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener())
myStream.filter(track=['Cycling', 'Running'])
I can get the if & elif to work offline when not adding the complexity of Tweepy into the equation, but am confused about exactly how to use the in statement.
I'm new to Python so will more than likely be making some simple mistakes!
Any help would be greatly appreciated,
Many thanks,
Matt
You are using in with the wrong variable (which points to the listener function). Use the status variable instead:
if 'cycling' in status.text.lower():
print('Cyclist' + status.text)
Note that I added .lower() to the end of status.text. That way it will match the word 'cycling' regardless of if it is capitalised or not.

Resources