text stringlengths 81 112k |
|---|
Fetch contents of email.
Args:
message_uid (int): IMAP Message UID number.
Kwargs:
message_type: Can be 'text' or 'html'
def get_email_message(self, message_uid, message_type="text/plain"):
"""
Fetch contents of email.
Args:
message_uid (in... |
Find the a set of emails matching each regular expression passed in against the (RFC822) content.
Args:
*args: list of regular expressions.
Kwargs:
limit (int) - Limit to how many of the most resent emails to search through.
date (datetime) - If specified, it will f... |
Get a list of message numbers
def __search_email_by_subject(self, subject, match_recipient):
"Get a list of message numbers"
if match_recipient is None:
_, data = self._mail.uid('search',
None,
'(HEADER SUBJECT "{subj... |
Gets the value from the yaml config based on the key.
No type casting is performed, any type casting should be
performed by the caller.
Args:
key (str) - Config setting key.
Kwargs:
default_value - Default value to return if config is not specified.
R... |
Generate page object from URL
def generate_page_object(page_name, url):
"Generate page object from URL"
# Attempt to extract partial URL for verification.
url_with_path = u('^.*//[^/]+([^?]+)?|$')
try:
match = re.match(url_with_path, url)
partial_url = match.group(1)
print("Usi... |
Get data path.
Args:
filename (string) : Name of file inside of /data folder to retrieve.
Kwargs:
env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa
Returns:
String - path to file.
Usage::
open(WTF_DATA_MANAG... |
Gets next entry as a dictionary.
Returns:
object - Object key/value pair representing a row.
{key1: value1, key2: value2, ...}
def next(self):
"""
Gets next entry as a dictionary.
Returns:
object - Object key/value pair representing a row.
... |
Utility method makes it easier to find an element using multiple selectors. This is
useful for problematic elements what might works with one browser, but fail in another.
(Like different page elements being served up for different browsers)
Args:
selectors - var arg if N number of... |
Wait for a WebElement to disappear.
Args:
webdriver (Webdriver) - Selenium Webdriver
locator (lambda) - Locator lambda expression.
Kwargs:
timeout (number) - timeout period
sleep (number) - sleep period between intervals.
def wait_until_element_not_visi... |
Check if an image (in an image tag) is loaded.
Note: This call will not work against background images. Only Images in <img> tags.
Args:
webelement (WebElement) - WebDriver web element to validate.
def is_image_loaded(webdriver, webelement):
'''
Check if an image (in an im... |
Generate time-stamped string. Format as follows...
`2013-01-31_14:12:23_SubjectString_a3Zg`
Kwargs:
subject (str): String to use as subject.
number_of_random_chars (int) : Number of random characters to append.
This method is helpful for creating unique names with timestamps in them so ... |
Generate a series of random characters.
Kwargs:
number_of_random_chars (int) : Number of characters long
character_set (str): Specify a character set. Default is ASCII
def generate_random_string(number_of_random_chars=8, character_set=string.ascii_letters):
"""
Generate a series of random... |
Converts the date format pattern used by Weka to the date format pattern used by Python's datetime.strftime().
def convert_weka_to_py_date_pattern(p):
"""
Converts the date format pattern used by Weka to the date format pattern used by Python's datetime.strftime().
"""
# https://docs.python.org/2/libra... |
Returns the value associated with the given value index
of the attribute with the given name.
This is only applicable for nominal and string types.
def get_attribute_value(self, name, index):
"""
Returns the value associated with the given value index
of the attribute w... |
Load an ARFF File from a file.
def load(cls, filename, schema_only=False):
"""
Load an ARFF File from a file.
"""
o = open(filename)
s = o.read()
a = cls.parse(s, schema_only=schema_only)
if not schema_only:
a._filename = filename
o.close()
... |
Parse an ARFF File already loaded into a string.
def parse(cls, s, schema_only=False):
"""
Parse an ARFF File already loaded into a string.
"""
a = cls()
a.state = 'comment'
a.lineno = 1
for l in s.splitlines():
a.parseline(l)
a.lineno += ... |
Creates a deepcopy of the instance.
If schema_only is True, the data will be excluded from the copy.
def copy(self, schema_only=False):
"""
Creates a deepcopy of the instance.
If schema_only is True, the data will be excluded from the copy.
"""
o = type(self)()
o... |
Save an arff structure to a file, leaving the file object
open for writing of new data samples.
This prevents you from directly accessing the data via Python,
but when generating a huge file, this prevents all your data
from being stored in memory.
def open_stream(self, class_attr_name=... |
Terminates an open stream and returns the filename
of the file containing the streamed data.
def close_stream(self):
"""
Terminates an open stream and returns the filename
of the file containing the streamed data.
"""
if self.fout:
fout = self.fout
... |
Save an arff structure to a file.
def save(self, filename=None):
"""
Save an arff structure to a file.
"""
filename = filename or self._filename
o = open(filename, 'w')
o.write(self.write())
o.close() |
Converts a single data line to a string.
def write_line(self, d, fmt=SPARSE):
"""
Converts a single data line to a string.
"""
def smart_quote(s):
if isinstance(s, basestring) and ' ' in s and s[0] != '"':
s = '"%s"' % s
return s
... |
Write an arff structure to a string.
def write(self,
fout=None,
fmt=SPARSE,
schema_only=False,
data_only=False):
"""
Write an arff structure to a string.
"""
assert not (schema_only and data_only), 'Make up your mind.'
assert fmt in FORMATS, 'Inva... |
Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'.
For nominal attributes, pass the possible values as data.
For date attributes, pass the format as data.
def define_attribute(self, name, atype, data=None):
"""
Define a new attrib... |
Print an overview of the ARFF file.
def dump(self):
"""Print an overview of the ARFF file."""
print("Relation " + self.relation)
print(" With attributes")
for n in self.attributes:
if self.attribute_types[n] != TYPE_NOMINAL:
print(" %s of type %s" % (n, s... |
Orders attributes names alphabetically, except for the class attribute, which is kept last.
def alphabetize_attributes(self):
"""
Orders attributes names alphabetically, except for the class attribute, which is kept last.
"""
self.attributes.sort(key=lambda name: (name == self.class_att... |
Convert the color from RGB coordinates to HSL.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, l) tuple in the range:
h[0...360],
s[0...1],
l[0...1]
>>> rgb_t... |
Convert the color from HSL coordinates to RGB.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>... |
Convert the color from RGB coordinates to HSV.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, v) tuple in the range:
h[0...360],
s[0...1],
v[0...1]
>>> rgb_t... |
Convert the color from RGB coordinates to HSV.
Parameters:
:h:
The Hus component value [0...1]
:s:
The Saturation component value [0...1]
:v:
The Value component [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> hsv_to_... |
Convert the color from RGB to YIQ.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (y, i, q) tuple in the range:
y[0...1],
i[0...1],
q[0...1]
>>> '(%g, %g, %g)' % rg... |
Convert the color from YIQ coordinates to RGB.
Parameters:
:y:
Tte Y component value [0...1]
:i:
The I component value [0...1]
:q:
The Q component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> '({}, {}, {})'.f... |
Convert the color from RGB coordinates to YUV.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (y, u, v) tuple in the range:
y[0...1],
u[-0.436...0.436],
v[-0.615...0.6... |
Convert the color from YUV coordinates to RGB.
Parameters:
:y:
The Y component value [0...1]
:u:
The U component value [-0.436...0.436]
:v:
The V component value [-0.615...0.615]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>... |
Convert the color from sRGB to CIE XYZ.
The methods assumes that the RGB coordinates are given in the sRGB
colorspace (D65).
.. note::
Compensation for the sRGB gamma correction is applied before converting.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component val... |
Convert the color from CIE XYZ coordinates to sRGB.
.. note::
Compensation for sRGB gamma correction is applied before converting.
Parameters:
:x:
The X component value [0...1]
:y:
The Y component value [0...1]
:z:
The Z component value [0...1]
Returns:
The color as an (... |
Convert the color from CIE XYZ to CIE L*a*b*.
Parameters:
:x:
The X component value [0...1]
:y:
The Y component value [0...1]
:z:
The Z component value [0...1]
:wref:
The whitepoint reference, default is 2° D65.
Returns:
The color as an (L, a, b) tuple in the range:
... |
Convert the color from CIE L*a*b* to CIE 1931 XYZ.
Parameters:
:l:
The L component [0...100]
:a:
The a component [-1...1]
:b:
The a component [-1...1]
:wref:
The whitepoint reference, default is 2° D65.
Returns:
The color as an (x, y, z) tuple in the range:
x[0...q]... |
Convert the color from CMYK coordinates to CMY.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:k:
The Black component value [0...1]
Returns:
The color as an (c, m, y) tuple in the range:
... |
Convert the color from CMY coordinates to CMYK.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
Returns:
The color as an (c, m, y, k) tuple in the range:
c[0...1],
m[0...1],
y[0...1],
... |
Convert the color from RGB coordinates to CMY.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (c, m, y) tuple in the range:
c[0...1],
m[0...1],
y[0...1]
>>> rgb_to_... |
Convert the color from CMY coordinates to RGB.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>>> cm... |
Convert the color in the standard [0...1] range to ints in the [0..255] range.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...255],
g[0... |
Convert ints in the [0...255] range to the standard [0...1] range.
Parameters:
:r:
The Red component value [0...255]
:g:
The Green component value [0...255]
:b:
The Blue component value [0...255]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
... |
Convert the color from (r, g, b) to #RRGGBB.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A CSS string representation of this color (#RRGGBB).
>>> rgb_to_html(1, 0.5, 0)
'#ff8000'
def rgb... |
Convert the HTML color to (r, g, b).
Parameters:
:html:
the HTML definition of the color (#RRGGBB or #RGB or a color name).
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
Throws:
:ValueError:
If html is neither a known color name or a hex... |
Convert the color from RGB to a PIL-compatible integer.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A PIL compatible integer (0xBBGGRR).
>>> '0x%06x' % rgb_to_pil(1, 0.5, 0)
'0x0080ff'
d... |
Convert the color from a PIL-compatible integer to RGB.
Parameters:
pil: a PIL compatible color representation (0xBBGGRR)
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r: [0...1]
g: [0...1]
b: [0...1]
>>> '(%g, %g, %g)' % pil_to_rgb(0x0080ff)
'(1, 0.501961, 0)'
def... |
Convert a color component to its web safe equivalent.
Parameters:
:c:
The component value [0...1]
:alt:
If True, return the alternative value instead of the nearest one.
Returns:
The web safe equivalent of the component value.
def _websafe_component(c, alt=False):
"""Convert a color com... |
Convert the color from RGB to 'web safe' RGB
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alt:
If True, use the alternative color instead of the nearest one.
Can be used for dithering.
Retu... |
Convert the color from RGB to its greyscale equivalent
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r[0...1],
g[0...1],
... |
Maps a hue on the RGB color wheel to Itten's RYB wheel.
Parameters:
:hue:
The hue on the RGB color wheel [0...360]
Returns:
An approximation of the corresponding hue on Itten's RYB wheel.
>>> rgb_to_ryb(15)
26.0
def rgb_to_ryb(hue):
"""Maps a hue on the RGB color wheel to Itten's RYB wheel.
... |
Maps a hue on Itten's RYB color wheel to the standard RGB wheel.
Parameters:
:hue:
The hue on Itten's RYB color wheel [0...360]
Returns:
An approximation of the corresponding hue on the standard RGB wheel.
>>> ryb_to_rgb(15)
8.0
def ryb_to_rgb(hue):
"""Maps a hue on Itten's RYB color wheel t... |
Create a new instance based on the specifed RGB values.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
T... |
Create a new instance based on the specifed HSL values.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:... |
Create a new instance based on the specifed HSV values.
Parameters:
:h:
The Hus component value [0...1]
:s:
The Saturation component value [0...1]
:v:
The Value component [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
T... |
Create a new instance based on the specifed YIQ values.
Parameters:
:y:
The Y component value [0...1]
:i:
The I component value [0...1]
:q:
The Q component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitep... |
Create a new instance based on the specifed YUV values.
Parameters:
:y:
The Y component value [0...1]
:u:
The U component value [-0.436...0.436]
:v:
The V component value [-0.615...0.615]
:alpha:
The color transparency [0...1], default is opaque
:wref:
... |
Create a new instance based on the specifed CIE-XYZ values.
Parameters:
:x:
The Red component value [0...1]
:y:
The Green component value [0...1]
:z:
The Blue component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
... |
Create a new instance based on the specifed CIE-LAB values.
Parameters:
:l:
The L component [0...100]
:a:
The a component [-1...1]
:b:
The a component [-1...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint refer... |
Create a new instance based on the specifed CMY values.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
... |
Create a new instance based on the specifed CMYK values.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:k:
The Black component value [0...1]
:alpha:
The color tran... |
Create a new instance based on the specifed HTML color definition.
Parameters:
:html:
The HTML definition of the color (#RRGGBB or #RGB or a color name).
:alpha:
The color transparency [0...1], default is opaque.
:wref:
The whitepoint reference, default is 2° D65.
Ret... |
Create a new instance based on the specifed PIL color.
Parameters:
:pil:
A PIL compatible color representation (0xBBGGRR)
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color in... |
Create a new instance based on this one with a new white reference.
Parameters:
:wref:
The whitepoint reference.
:labAsRef:
If True, the L*a*b* values of the current instance are used as reference
for the new color; otherwise, the RGB values are used as reference.
Returns:
... |
Create a new instance based on this one but less saturated.
Parameters:
:level:
The amount by which the color should be desaturated to produce
the new one [0...1].
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25)
Color(0.625, 0.5, 0.3... |
Return the two websafe colors nearest to this one.
Returns:
A tuple of two grapefruit.Color instances which are the two
web safe colors closest this one.
>>> c = Color.from_rgb(1.0, 0.45, 0.0)
>>> c1, c2 = c.websafe_dither()
>>> c1
Color(1.0, 0.4, 0.0, 1.0)
>>> c2
Color(1.0, 0.... |
Create a new instance which is the complementary color of this one.
Parameters:
:mode:
Select which color wheel to use for the generation (ryb/rgb).
Returns:
A grapefruit.Color instance.
>>> Color.from_hsl(30, 1, 0.5).complementary_color(mode='rgb')
Color(0.0, 0.5, 1.0, 1.0)
... |
Return two colors analogous to this one.
Args:
:angle:
The angle between the hues of the created colors and this one.
:mode:
Select which color wheel to use for the generation (ryb/rgb).
Returns:
A tuple of grapefruit.Colors analogous to this one.
>>> c1 = Color.from_hsl... |
Alpha-blend this color on the other one.
Args:
:other:
The grapefruit.Color to alpha-blend with this one.
Returns:
A grapefruit.Color instance which is the result of alpha-blending
this color on the other one.
>>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)
>>> c2 = Color.from_rgb(1... |
blend this color with the other one.
Args:
:other:
the grapefruit.Color to blend with this one.
Returns:
A grapefruit.Color instance which is the result of blending
this color on the other one.
>>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)
>>> c2 = Color.from_rgb(1, 1, 1, 0.6)
... |
Parse command-line arguments.
def get_parser():
"""Parse command-line arguments."""
parser = ArgumentParser(description='a command-line web scraping tool')
parser.add_argument('query', metavar='QUERY', type=str, nargs='*',
help='URLs/files to scrape')
parser.add_argument('-a', '... |
Write scraped or local file(s) in desired format.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output file (str)
Remove PART(#).html files after conversion unless otherwise specified.
def write_file... |
Write to a single output file and/or subdirectory.
def write_single_file(args, base_dir, crawler):
"""Write to a single output file and/or subdirectory."""
if args['urls'] and args['html']:
# Create a directory to save PART.html files in
domain = utils.get_domain(args['urls'][0])
if not... |
Write to multiple output files and/or subdirectories.
def write_multiple_files(args, base_dir, crawler):
"""Write to multiple output files and/or subdirectories."""
for i, query in enumerate(args['query']):
if query in args['files']:
# Write files
if args['out'] and i < len(args... |
Split query input into local files and URLs.
def split_input(args):
"""Split query input into local files and URLs."""
args['files'] = []
args['urls'] = []
for arg in args['query']:
if os.path.isfile(arg):
args['files'].append(arg)
else:
args['urls'].append(arg.s... |
Detect whether to save to a single or multiple files.
def detect_output_type(args):
"""Detect whether to save to a single or multiple files."""
if not args['single'] and not args['multiple']:
# Save to multiple files if multiple files/URLs entered
if len(args['query']) > 1 or len(args['out']) >... |
Scrape webpage content.
def scrape(args):
"""Scrape webpage content."""
try:
base_dir = os.getcwd()
if args['out'] is None:
args['out'] = []
# Detect whether to save to a single or multiple files
detect_output_type(args)
# Split query input into local files... |
Prompt user for filetype if none specified.
def prompt_filetype(args):
"""Prompt user for filetype if none specified."""
valid_types = ('print', 'text', 'csv', 'pdf', 'html')
if not any(args[x] for x in valid_types):
try:
filetype = input('Print or save output as ({0}): '
... |
Prompt user to save images when crawling (for pdf and HTML formats).
def prompt_save_images(args):
"""Prompt user to save images when crawling (for pdf and HTML formats)."""
if args['images'] or args['no_images']:
return
if (args['pdf'] or args['html']) and (args['crawl'] or args['crawl_all']):
... |
Handle command-line interaction.
def command_line_runner():
"""Handle command-line interaction."""
parser = get_parser()
args = vars(parser.parse_args())
if args['version']:
print(__version__)
return
if args['clear_cache']:
utils.clear_cache()
print('Cleared {0}.'.fo... |
Loads a trained classifier from the raw Weka model format.
Must specify the model schema and classifier name, since
these aren't currently deduced from the model format.
def load_raw(cls, model_fn, schema, *args, **kwargs):
"""
Loads a trained classifier from the raw Weka model format.
... |
Updates the classifier with new data.
def train(self, training_data, testing_data=None, verbose=False):
"""
Updates the classifier with new data.
"""
model_fn = None
training_fn = None
clean_training = False
testing_fn = None
clean_testing = False
... |
Iterates over the predicted values and probability (if supported).
Each iteration yields a tuple of the form (prediction, probability).
If the file is a test file (i.e. contains no query variables),
then the tuple will be of the form (prediction, actual).
See http://wek... |
Returns a ratio of classifiers that were able to be trained successfully.
def get_training_coverage(self):
"""
Returns a ratio of classifiers that were able to be trained successfully.
"""
total = len(self.training_results)
i = sum(1 for data in self.training_results.values() if... |
Get new links from a URL and filter them.
def get_new_links(self, url, resp):
"""Get new links from a URL and filter them."""
links_on_page = resp.xpath('//a/@href')
links = [utils.clean_url(u, url) for u in links_on_page]
# Remove non-links through filtering by protocol
links ... |
Check if page has been crawled by hashing its text content.
Add new pages to the page cache.
Return whether page was found in cache.
def page_crawled(self, page_resp):
"""Check if page has been crawled by hashing its text content.
Add new pages to the page cache.
Return whethe... |
Find new links given a seed URL and follow them breadth-first.
Save page responses as PART.html files.
Return the PART.html filenames created during crawling.
def crawl_links(self, seed_url=None):
"""Find new links given a seed URL and follow them breadth-first.
Save page responses as... |
Get available proxies to use with requests library.
def get_proxies():
"""Get available proxies to use with requests library."""
proxies = getproxies()
filtered_proxies = {}
for key, value in proxies.items():
if key.startswith('http://'):
if not value.startswith('http://'):
... |
Get webpage response as an lxml.html.HtmlElement object.
def get_resp(url):
"""Get webpage response as an lxml.html.HtmlElement object."""
try:
headers = {'User-Agent': random.choice(USER_AGENTS)}
try:
request = requests.get(url, headers=headers, proxies=get_proxies())
excep... |
Enable requests library cache.
def enable_cache():
"""Enable requests library cache."""
try:
import requests_cache
except ImportError as err:
sys.stderr.write('Failed to enable cache: {0}\n'.format(str(err)))
return
if not os.path.exists(CACHE_DIR):
os.makedirs(CACHE_DIR... |
Return MD5 hash of a string.
def hash_text(text):
"""Return MD5 hash of a string."""
md5 = hashlib.md5()
md5.update(text)
return md5.hexdigest() |
Add a page to the page cache.
def cache_page(page_cache, page_hash, cache_size):
"""Add a page to the page cache."""
page_cache.append(page_hash)
if len(page_cache) > cache_size:
page_cache.pop(0) |
Filter text using regular expressions.
def re_filter(text, regexps):
"""Filter text using regular expressions."""
if not regexps:
return text
matched_text = []
compiled_regexps = [re.compile(x) for x in regexps]
for line in text:
if line in matched_text:
continue
... |
Remove unnecessary whitespace while keeping logical structure.
Keyword arguments:
text -- text to remove whitespace from (list)
Retain paragraph structure but remove other whitespace,
such as between words on a line and at the start and end of the text.
def remove_whitespace(text):
"""Remove unne... |
Filter text using XPath, regex keywords, and tag attributes.
Keyword arguments:
infile -- HTML or text content to parse (list)
xpath -- an XPath expression (str)
filter_words -- regex keywords (list)
attributes -- HTML tag attributes (list)
Return a list of strings of text.
def parse_text(inf... |
Parse and return text content of infiles.
Keyword arguments:
args -- program arguments (dict)
infilenames -- name of user-inputted and/or downloaded file (str)
Return a list of strings of text.
def get_parsed_text(args, infilename):
"""Parse and return text content of infiles.
Keyword argume... |
Filter HTML using XPath.
def parse_html(infile, xpath):
"""Filter HTML using XPath."""
if not isinstance(infile, lh.HtmlElement):
infile = lh.fromstring(infile)
infile = infile.xpath(xpath)
if not infile:
raise ValueError('XPath {0} returned no results.'.format(xpath))
return infile |
Add base netloc and path to internal URLs and remove www, fragments.
def clean_url(url, base_url=None):
"""Add base netloc and path to internal URLs and remove www, fragments."""
parsed_url = urlparse(url)
fragment = '{url.fragment}'.format(url=parsed_url)
if fragment:
url = url.split(fragment... |
Add .com suffix to URL if none found.
def add_url_suffix(url):
"""Add .com suffix to URL if none found."""
url = url.rstrip('/')
if not has_suffix(url):
return '{0}.com'.format(url)
return url |
Construct the output filename from domain and end of path.
def get_outfilename(url, domain=None):
"""Construct the output filename from domain and end of path."""
if domain is None:
domain = get_domain(url)
path = '{url.path}'.format(url=urlparse(url))
if '.' in path:
tail_url = path.s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.