0% found this document useful (0 votes)
6 views16 pages

Codesrepl

The document contains various Python code snippets demonstrating different programming concepts such as input handling, string manipulation, file operations, and data structures. It also includes a section for processing RSS feeds using OpenAI's GPT-3 API to summarize content and post it on Twitter. The code illustrates error handling, dictionary usage, and basic data analysis techniques.

Uploaded by

Joseph Nketia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views16 pages

Codesrepl

The document contains various Python code snippets demonstrating different programming concepts such as input handling, string manipulation, file operations, and data structures. It also includes a section for processing RSS feeds using OpenAI's GPT-3 API to summarize content and post it on Twitter. The code illustrates error handling, dictionary usage, and basic data analysis techniques.

Uploaded by

Joseph Nketia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

import re

"""

try:

hours = float(input("Enter hours: "))

rate = float(input("Enter Rate: "))

except:

print("Error please enter numeric input")

if hours > 40 :

pay = (rate * hours) + ((hours - 40) * 1.5 * rate)

else :

pay = rate * hours

print(pay)

big = max("Hello world")

print(big)

"""

#def addtwo(a,b):

# return a + b

#q = addtwo(9,5)

#print(q)

"""

largest = 0

for i in [3, 41, 12, 9, 74, 15]:

if i > largest :

largest = i

print(largest)
"""

s = "Monty Python"

print(s[2:5])

"""

greeet = "Hello Bob"

zap = greeet.find('ob')

print(zap)

greet = " Hello Bob "

nstr = greeet.lstrip()

print(nstr)

q)

"""

"""

stce = "Please Jesus is King"

print(f"{stce.startswith('Please')}")

"""

"""

data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'

atpos = data.find('@')

print(atpos)

sppos = data.find(' ', atpos)

print(sppos)

print(data[atpos+1:sppos])

"""

"""

fname = input("Enter a file name: ")

try:
handle = open(fname)

except:

print("File cannot be opened: " + fname)

quit()

"""

"""

count = 0

for i in handle:

count = count + 1

print(count)

"""

#inp = handle.read()

#print(len(inp))

#print(inp[-2])

"""

for line in handle:

line = line.rstrip()

if line.startswith("From:"):

print(line)

"""

x = [5, 6, 7, 8, 9, 10]

print(sum(x))

abc = "With three words"

stuff = abc.split()

print(stuff)
line = 'first;second;third'

thing = line.split(';')

print(thing)

"""

counts = dict()

names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']

for name in names :

counts[name] = counts.get(name, 0) + 1

print(counts)

count = dict()

print('Enter a line of text')

line = input(' ')

words = line.split()

for word in words:

count[word] = count.get(word, 0) + 1

print(max(count.items()))

jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}

for aaa,bbb in jjj.items() :

print(aaa, bbb)

"""

name = input("Enter file name: ")

fhandle = open(name)

"""

for lines in fhandle:

lines = lines.rstrip()
if re.search("^From:", lines):

print(lines)

"""

counts = dict()

for line in fhandle:

words = line.split()

for word in words:

counts[word] = counts.get(word, 0) + 1

maxv = max(counts.values())

maxk = [k for k,v in counts.items() if v == maxv]

print(maxk, maxv)

lst = list()

for k,v in counts.items():

lst.append((v,k))

lst = sorted(lst, reverse=True)

for k,v in lst[:10]:

print(v,k)

print(sorted([(v,k) for k,v in counts.items()]))

d = dict()

d['csev'] = 2

d['cwen'] = 4

for (k,v) in d.items():


print(k, v)

d = {"a" : 10, "b": 1, "c": 22}

sd = sorted(d.items())

print(sd)

for k,v in sorted(d.items()):

print(k,v)

d = {"a" : 10, "b": 1, "c": 22}

ld = list()

for k,v in d.items():

ld.append((v,k))

print(ld)

ld = sorted(ld, reverse=True)

print(ld)

data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'

words = data.split()

email = words[1]

print(email.split('@')[1])

import re
import socket

"""

try:

hours = float(input("Enter hours: "))

rate = float(input("Enter Rate: "))

except:

print("Error please enter numeric input")

if hours > 40 :

pay = (rate * hours) + ((hours - 40) * 1.5 * rate)

else :

pay = rate * hours

print(pay)

big = max("Hello world")

print(big)

"""

#def addtwo(a,b):

# return a + b

#q = addtwo(9,5)

#print(q)

"""

largest = 0

for i in [3, 41, 12, 9, 74, 15]:

if i > largest :

largest = i

print(largest)

"""
s = "Monty Python"

print(s[2:5])

"""

greeet = "Hello Bob"

zap = greeet.find('ob')

print(zap)

greet = " Hello Bob "

nstr = greeet.lstrip()

print(nstr)

q)

"""

"""

stce = "Please Jesus is King"

print(f"{stce.startswith('Please')}")

"""

"""

data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'

atpos = data.find('@')

print(atpos)

sppos = data.find(' ', atpos)

print(sppos)

print(data[atpos+1:sppos])

"""

"""

fname = input("Enter a file name: ")

try:

handle = open(fname)
except:

print("File cannot be opened: " + fname)

quit()

"""

"""

count = 0

for i in handle:

count = count + 1

print(count)

"""

#inp = handle.read()

#print(len(inp))

#print(inp[-2])

"""

for line in handle:

line = line.rstrip()

if line.startswith("From:"):

print(line)

"""

x = [5, 6, 7, 8, 9, 10]

print(sum(x))

abc = "With three words"

stuff = abc.split()

print(stuff)
line = 'first;second;third'

thing = line.split(';')

print(thing)

"""

counts = dict()

names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']

for name in names :

counts[name] = counts.get(name, 0) + 1

print(counts)

count = dict()

print('Enter a line of text')

line = input(' ')

words = line.split()

for word in words:

count[word] = count.get(word, 0) + 1

print(max(count.items()))

jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}

for aaa,bbb in jjj.items() :

print(aaa, bbb)

"""

name = input("Enter file name: ")

fhandle = open(name)

"""

for lines in fhandle:

lines = lines.rstrip()

if re.search("^From:", lines):
print(lines)

"""

counts = dict()

for line in fhandle:

words = line.split()

for word in words:

counts[word] = counts.get(word, 0) + 1

maxv = max(counts.values())

maxk = [k for k,v in counts.items() if v == maxv]

print(maxk, maxv)

lst = list()

for k,v in counts.items():

lst.append((v,k))

lst = sorted(lst, reverse=True)

for k,v in lst[:10]:

print(v,k)

print(sorted([(v,k) for k,v in counts.items()]))

d = dict()

d['csev'] = 2

d['cwen'] = 4

for (k,v) in d.items():

print(k, v)
d = {"a" : 10, "b": 1, "c": 22}

sd = sorted(d.items())

print(sd)

for k,v in sorted(d.items()):

print(k,v)

d = {"a" : 10, "b": 1, "c": 22}

ld = list()

for k,v in d.items():

ld.append((v,k))

print(ld)

ld = sorted(ld, reverse=True)

print(ld)

data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'

words = data.split()

email = words[1]

print(email.split('@')[1])
counts = dict()

fhand= urllib.request.urlopen('http://www.dr-chuck.com/page1.htm')

"""

for line in fhand:

words = line.decode().split()

for word in words:

counts[word] = counts.get(word , 0) + 1

print(counts)

"""

for line in fhand:

print(line.decode().strip())
import openai

import feedparser

import tweepy

import random

import time

# RSS feed URLs

feed_urls = [

"https://www.chelseafc.com/en/rss.xml",

"https://weaintgotnohistory.sbnation.com/rss/current",

"https://talkchelsea.net/feed/",

# OpenAI API credentials

openai.api_key = "YOUR_API_KEY_HERE"

# Twitter API credentials

consumer_key = "YOUR_CONSUMER_KEY_HERE"

consumer_secret = "YOUR_CONSUMER_SECRET_HERE"

access_token = "YOUR_ACCESS_TOKEN_HERE"

access_token_secret = "YOUR_ACCESS_TOKEN_SECRET_HERE"
# GPT-3 model ID and prompt

model_id = "davinci"

prompt = "Summarize the following text:"

# Authenticate with Twitter API

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

# Shuffle the feed URLs to randomize the order in which they are processed

random.shuffle(feed_urls)

# Process each feed URL

for feed_url in feed_urls:

# Parse the RSS feed

feed = feedparser.parse(feed_url)

# Iterate over the entries in reverse order (oldest to newest)

for entry in reversed(feed.entries):

# Extract the full text of the entry

full_text = entry.get("content")[0].get("value")

# Call the OpenAI GPT-3 API to summarize the text

response = openai.Completion.create(

engine=model_id,

prompt=f"{prompt}\n{full_text}",

max_tokens=60,

n=1,
stop=None,

temperature=0.5,

# Extract the generated summary

summary = response.choices[0].text.strip()

# Prepare the tweet content

tweet_content = f"{summary}\n\n{entry.link}\n\nAttribution: {entry.title}"

# Post the tweet

api.update_status(tweet_content)

# Print confirmation

print("Tweet posted successfully!")

# Add a delay between tweets to comply with Twitter rate limits

time.sleep(5)

You might also like