Please forgive me I am teaching myself and am pretty new to this. I have searched and found nothing that addressed my issue, lots of things dealing with os and file directories but I couldn't figure out how to implement them here. I also am not super familiar with regex, and have tried implementing that as well but kept getting errors.
So I have a large text file (9GB) that is actually a list of discussion board posts.
I have a list of words I want to add to the stoplist for topic modeling. (I can do that)
However I also want to add any term that ends with any of the words in my list.
A sample of my data and lists is below.
txt = ['satoshiFounderSr MemberOfflineActivity Merit Welcome to the new Bitcoin forumNovember PMMeritedbyVlad Vlad Claymore krogothmanhattan negeroy Referee Vod suchmoon alani Lesbian Cow cryptohunter hv janggernaut matt Jeremycoin MaoChao Kda roslinpl gold MicroGuy elokk notaek BitcoinFX EcuaMobi Lutpin Lincoln Echo Nomad avatar kiyoshi saugwurm BALIK anggriani teeGUMES dooglus bitbollo klarki franckuestein legendster techman Provok mrcash paxmao jeks Cent MrCryptHodl DireWolfM BarbieCasino theunbeatable mindrust fillippone Mister k LFC Bitcoin nutildah Oceat digit Woshib ubay undeadbitcoiner pushups btcrocks realdantreccia Dq Atabey limtjoehua LoyceV anonymousminer MagicByt vizique coinlocket Altcoinsintel baeva OgNasty o solo miner Janation Kalemder sujonali MoparMiningLLC Eddyc jonemil Kryptowolf green slmn TyfrTR cr mprep Searing EFS adaseb notbatman Lucius boltz layer gfx seoincorporation AGD Phinnaeus Gage tabas pawel Lafu pangu Blind Legs Parker itod Potato Chips wonko Arriemoller Coin ruletheworld Halab coupable o e l e o TheBeardedBaby MoxnatyShmel monsanto amishmanish xtraelv Husna QA madnessteat Bthd taikuri dvd rw Toxic styca WorldCoiner bubbalex xyzzy V saya jets crypto trader xzEXrP xlcus solosequenosenada VB MishaSER dragonvslinux Zocadas jahepahit risatrakib chimk Porfirii YuT Coin adrianto famososMuertos angel Financisto RareFortune jakoylantern bere kin mdayonliner sncc squallw cryptjh jazmuzika wishxy markleal BlackHatCoiner an sha ldah DEMENTOR mustangy TaShoKi Adriane Poker Player StackItUp PIOUPIOU loreRex tasadar wego Gustavo Livecoins Palmholder CryptoPravda barjan Crypto Collection collapse jukeee Cuk ng bitc in LBTC Pyrojason M BTC vanobe shortcircuit Toqo Vxv BiT pOL songsunling bitcoinokulu AlexMay Kaonashi Neo Baudrillard RussaX morkaii Welcome to the new Bitcoin forumThe old forum can still be reached here http bitcoinsourceforgenet boards indexphpI ll repost some selected threads here and add updated answers to questions where I canFAQhttp bitcoinsourceforgenet wiki indexphppage FAQDownloadhttp sourceforgenet projects bitcoin files satoshiFounderSr MemberOfflineActivity Merit Welcome to the new Bitcoin forumNovember PMMeritedbyVlad Vlad Claymore krogothmanhattan negeroy Referee Vod suchmoon alani Lesbian Cow cryptohunter hv janggernaut matt Jeremycoin MaoChao Kda roslinpl gold MicroGuy elokk notaek BitcoinFX EcuaMobi Lutpin Lincoln Echo Nomad avatar kiyoshi saugwurm BALIK anggriani teeGUMES dooglus bitbollo klarki franckuestein legendster techman Provok mrcash paxmao jeks Cent MrCryptHodl DireWolfM BarbieCasino theunbeatable mindrust fillippone Mister k LFC Bitcoin nutildah Oceat digit Woshib ubay undeadbitcoiner pushups btcrocks realdantreccia Dq Atabey limtjoehua LoyceV anonymousminer MagicByt vizique coinlocket Altcoinsintel baeva OgNasty o solo miner Janation Kalemder sujonali MoparMiningLLC Eddyc jonemil Kryptowolf green slmn TyfrTR cr mprep Searing EFS adaseb notbatman Lucius boltz layer gfx seoincorporation AGD Phinnaeus Gage tabas pawel Lafu pangu Blind Legs Parker itod Potato Chips wonko Arriemoller Coin ruletheworld Halab coupable o e l e o TheBeardedBaby MoxnatyShmel monsanto amishmanish xtraelv Husna QA madnessteat Bthd taikuri dvd rw Toxic styca WorldCoiner bubbalex xyzzy V saya jets crypto trader xzEXrP xlcus solosequenosenada VB MishaSER dragonvslinux Zocadas jahepahit risatrakib chimk Porfirii YuT Coin adrianto famososMuertos angel Financisto RareFortune jakoylantern bere kin mdayonliner sncc squallw cryptjh jazmuzika wishxy markleal BlackHatCoiner an sha ldah DEMENTOR mustangy TaShoKi Adriane Poker Player StackItUp PIOUPIOU loreRex tasadar wego Gustavo Livecoins Palmholder CryptoPravda barjan Crypto Collection collapse jukeee Cuk ng bitc in LBTC Pyrojason M BTC vanobe shortcircuit Toqo Vxv BiT pOL songsunling bitcoinokulu AlexMay Kaonashi Neo Baudrillard RussaX morkaii Welcome to the new Bitcoin forumThe old forum can still be reached here http bitcoinsourceforgenet boards indexphpI ll repost some selected threads here and add updated answers to questions where I canFAQhttp bitcoinsourceforgenet wiki indexphppage FAQDownloadhttp sourceforgenet projects bitcoin files satoshiFounderSr MemberOfflineActivity Merit Welcome to the new Bitcoin forumNovember PMMeritedbyVlad Vlad Claymore krogothmanhattan negeroy Referee Vod suchmoon alani Lesbian Cow cryptohunter hv janggernaut matt Jeremycoin MaoChao Kda roslinpl gold MicroGuy elokk notaek BitcoinFX EcuaMobi Lutpin Lincoln Echo Nomad avatar kiyoshi saugwurm BALIK anggriani teeGUMES dooglus bitbollo klarki franckuestein legendster techman Provok mrcash paxmao jeks Cent MrCryptHodl DireWolfM BarbieCasino theunbeatable mindrust fillippone Mister k LFC Bitcoin nutildah Oceat digit Woshib ubay undeadbitcoiner pushups btcrocks realdantreccia Dq Atabey limtjoehua LoyceV anonymousminer MagicByt vizique coinlocket Altcoinsintel baeva OgNasty o solo miner Janation Kalemder sujonali MoparMiningLLC Eddyc jonemil Kryptowolf green slmn TyfrTR cr mprep Searing EFS adaseb notbatman Lucius boltz layer gfx seoincorporation AGD Phinnaeus Gage tabas pawel Lafu pangu Blind Legs Parker itod Potato Chips wonko Arriemoller Coin ruletheworld Halab coupable o e l e o TheBeardedBaby MoxnatyShmel monsanto amishmanish xtraelv Husna QA madnessteat Bthd taikuri dvd rw Toxic styca WorldCoiner bubbalex xyzzy V saya jets crypto trader xzEXrP xlcus solosequenosenada VB MishaSER dragonvslinux Zocadas jahepahit risatrakib chimk Porfirii YuT Coin adrianto famososMuertos angel Financisto RareFortune jakoylantern bere kin mdayonliner sncc squallw cryptjh jazmuzika wishxy markleal BlackHatCoiner an sha ldah DEMENTOR mustangy TaShoKi Adriane Poker Player StackItUp PIOUPIOU loreRex tasadar wego Gustavo Livecoins Palmholder CryptoPravda barjan Crypto Collection collapse jukeee Cuk ng bitc in LBTC Pyrojason M BTC vanobe shortcircuit Toqo Vxv BiT pOL songsunling bitcoinokulu AlexMay Kaonashi Neo Baudrillard RussaX morkaii Welcome to the new Bitcoin forumThe old forum can still be reached here http bitcoinsourceforgenet boards indexphpI ll repost some selected threads here and add updated answers to questions where I canFAQhttp bitcoinsourceforgenet wiki indexphppage FAQDownloadhttp sourceforgenet projects bitcoin files Welcome to the new Bitcoin forumNovember PMMeritedbyVlad Vlad Claymore krogothmanhattan negeroy Referee Vod suchmoon alani Lesbian Cow cryptohunter hv janggernaut matt Jeremycoin MaoChao Kda roslinpl gold MicroGuy elokk notaek BitcoinFX EcuaMobi Lutpin Lincoln Echo Nomad avatar kiyoshi saugwurm BALIK anggriani teeGUMES dooglus bitbollo klarki franckuestein legendster techman Provok mrcash paxmao jeks Cent MrCryptHodl DireWolfM BarbieCasino theunbeatable mindrust fillippone Mister k LFC Bitcoin nutildah Oceat digit Woshib ubay undeadbitcoiner pushups btcrocks realdantreccia Dq Atabey limtjoehua LoyceV anonymousminer MagicByt vizique coinlocket Altcoinsintel baeva OgNasty o solo miner Janation Kalemder sujonali MoparMiningLLC Eddyc jonemil Kryptowolf green slmn TyfrTR cr mprep Searing EFS adaseb notbatman Lucius boltz layer gfx seoincorporation AGD Phinnaeus Gage tabas pawel Lafu pangu Blind Legs Parker itod Potato Chips wonko Arriemoller Coin ruletheworld Halab coupable o e l e o TheBeardedBaby MoxnatyShmel monsanto amishmanish xtraelv Husna QA madnessteat Bthd taikuri dvd rw Toxic styca WorldCoiner bubbalex xyzzy V saya jets crypto trader xzEXrP xlcus solosequenosenada VB MishaSER dragonvslinux Zocadas jahepahit risatrakib chimk Porfirii YuT Coin adrianto famososMuertos angel Financisto RareFortune jakoylantern bere kin mdayonliner sncc squallw cryptjh jazmuzika wishxy markleal BlackHatCoiner an sha ldah DEMENTOR mustangy TaShoKi Adriane Poker Player StackItUp PIOUPIOU loreRex tasadar wego Gustavo Livecoins Palmholder CryptoPravda barjan Crypto Collection collapse jukeee Cuk ng bitc in LBTC Pyrojason M BTC vanobe shortcircuit Toqo Vxv BiT pOL songsunling bitcoinokulu AlexMay Kaonashi Neo Baudrillard RussaX morkaii ',
'satoshiFounderSr MemberOfflineActivity Merit Repost Bitcoin MaturationNovember PMMeritedbyescrowms NeuroticFish finist x icopress jankeman bitcoinbitcoin Bitcoin MaturationPosted Thu of Oct UTC From the user s perspective the bitcoin maturation process can be broken down into stages The initial network transaction that occurs when you first click Generate Coins The time between that initial network transaction and when the bitcoin entry is ready to appear in the All Transactions list The change of the bitcoin entry from outside the All Transaction field to inside it The time between when the bitcoin appears in the All Transfers list and when the Description is ready to change to Generated matures in x more blocks The change of the Description to Generated matures in x more blocks The time between when the Description says Generated matures in x more blocks to when it is ready to change to Generated The change of the Description to Generated The time after the Description has changed to GeneratedWhich stages require network connectivity significant local CPU usage and or significant remote CPU usage Do any of these stages have names sirius m Re Bitcoin MaturationPosted Thu of Oct UTC As far as I know there s no network transaction when you click Generate Coins your computer just starts calculating the next proof of work The CPU usage is when you re generating coinsIn this example the network connection is used when you broadcast the information about the proof of work block you ve created that which entitles you to the new coin Generating coins successfully requires constant connectivity so that you can start working on the next block when someone gets the current block before yousatoshiFounderSr MemberOfflineActivity Merit Repost Bitcoin MaturationNovember PMMeritedbyescrowms NeuroticFish finist x icopress jankeman bitcoinbitcoin Bitcoin MaturationPosted Thu of Oct UTC From the user s perspective the bitcoin maturation process can be broken down into stages The initial network transaction that occurs when you first click Generate Coins The time between that initial network transaction and when the bitcoin entry is ready to appear in the All Transactions list The change of the bitcoin entry from outside the All Transaction field to inside it The time between when the bitcoin appears in the All Transfers list and when the Description is ready to change to Generated matures in x more blocks The change of the Description to Generated matures in x more blocks The time between when the Description says Generated matures in x more blocks to when it is ready to change to Generated The change of the Description to Generated The time after the Description has changed to GeneratedWhich stages require network connectivity significant local CPU usage and or significant remote CPU usage Do any of these stages have names sirius m Re Bitcoin MaturationPosted Thu of Oct UTC As far as I know there s no network transaction when you click Generate Coins your computer just starts calculating the next proof of work The CPU usage is when you re generating coinsIn this example the network connection is used when you broadcast the information about the proof of work block you ve created that which entitles you to the new coin Generating coins successfully requires constant connectivity so that you can start working on the next block when someone gets the current block before yousatoshiFounderSr MemberOfflineActivity Merit Repost Bitcoin MaturationNovember PMMeritedbyescrowms NeuroticFish finist x icopress jankeman bitcoinbitcoin Bitcoin MaturationPosted Thu of Oct UTC From the user s perspective the bitcoin maturation process can be broken down into stages The initial network transaction that occurs when you first click Generate Coins The time between that initial network transaction and when the bitcoin entry is ready to appear in the All Transactions list The change of the bitcoin entry from outside the All Transaction field to inside it The time between when the bitcoin appears in the All Transfers list and when the Description is ready to change to Generated matures in x more blocks The change of the Description to Generated matures in x more blocks The time between when the Description says Generated matures in x more blocks to when it is ready to change to Generated The change of the Description to Generated The time after the Description has changed to GeneratedWhich stages require network connectivity significant local CPU usage and or significant remote CPU usage Do any of these stages have names sirius m Re Bitcoin MaturationPosted Thu of Oct UTC As far as I know there s no network transaction when you click Generate Coins your computer just starts calculating the next proof of work The CPU usage is when you re generating coinsIn this example the network connection is used when you broadcast the information about the proof of work block you ve created that which entitles you to the new coin Generating coins successfully requires constant connectivity so that you can start working on the next block when someone gets the current block before youRepost Bitcoin MaturationNovember PMMeritedbyescrowms NeuroticFish finist x icopress jankeman ',
'satoshiFounderSr MemberOfflineActivity Merit Repost Request Make this anonymousNovember PMMeritedbyxtraelv anonguy Request Make this anonymousPosted Thu of Oct UTC Are there any plans to make this service anonymouseg Being able to route BitCoin through TorsatoshiFounderSr MemberOfflineActivity Merit Repost Request Make this anonymousNovember PMMeritedbyxtraelv anonguy Request Make this anonymousPosted Thu of Oct UTC Are there any plans to make this service anonymouseg Being able to route BitCoin through TorsatoshiFounderSr MemberOfflineActivity Merit Repost Request Make this anonymousNovember PMMeritedbyxtraelv anonguy Request Make this anonymousPosted Thu of Oct UTC Are there any plans to make this service anonymouseg Being able to route BitCoin through TorRepost Request Make this anonymousNovember PMMeritedbyxtraelv ',
'satoshiFounderSr MemberOfflineActivity Merit Re Repost Bitcoin MaturationNovember PMMeritedbyhold coins NeuroticFish It s important to have network connectivity while you re trying to generate a coin block and at the moment it is successfully generated During generation when the status bar says Generating and you re using CPU to find a proof of work you must constantly keep in contact with the network to receive the latest block If your block does not link to the latest block it may not be accepted When you successfully generate a block it is immediately broadcast to the network Other nodes must receive it and link to it for it to be accepted as the new latest blockThink of it as a cooperative effort to make a chain When you add a link you must first find the current end of the chain If you were to locate the last link then go off for an hour and forge your link come back and link it to the link that was the end an hour ago others may have added several links since then and they re not going to want to use your link that now branches off the middleAfter a block is created the maturation time of blocks is to make absolutely sure the block is part of the main chain before it can be spent Your node isn t doing anything with the block during that time just waiting for other blocks to be added after yours You don t have to be online during that timesatoshiFounderSr MemberOfflineActivity Merit Re Repost Bitcoin MaturationNovember PMMeritedbyhold coins NeuroticFish It s important to have network connectivity while you re trying to generate a coin block and at the moment it is successfully generated During generation when the status bar says Generating and you re using CPU to find a proof of work you must constantly keep in contact with the network to receive the latest block If your block does not link to the latest block it may not be accepted When you successfully generate a block it is immediately broadcast to the network Other nodes must receive it and link to it for it to be accepted as the new latest blockThink of it as a cooperative effort to make a chain When you add a link you must first find the current end of the chain If you were to locate the last link then go off for an hour and forge your link come back and link it to the link that was the end an hour ago others may have added several links since then and they re not going to want to use your link that now branches off the middleAfter a block is created the maturation time of blocks is to make absolutely sure the block is part of the main chain before it can be spent Your node isn t doing anything with the block during that time just waiting for other blocks to be added after yours You don t have to be online during that timesatoshiFounderSr MemberOfflineActivity Merit Re Repost Bitcoin MaturationNovember PMMeritedbyhold coins NeuroticFish It s important to have network connectivity while you re trying to generate a coin block and at the moment it is successfully generated During generation when the status bar says Generating and you re using CPU to find a proof of work you must constantly keep in contact with the network to receive the latest block If your block does not link to the latest block it may not be accepted When you successfully generate a block it is immediately broadcast to the network Other nodes must receive it and link to it for it to be accepted as the new latest blockThink of it as a cooperative effort to make a chain When you add a link you must first find the current end of the chain If you were to locate the last link then go off for an hour and forge your link come back and link it to the link that was the end an hour ago others may have added several links since then and they re not going to want to use your link that now branches off the middleAfter a block is created the maturation time of blocks is to make absolutely sure the block is part of the main chain before it can be spent Your node isn t doing anything with the block during that time just waiting for other blocks to be added after yours You don t have to be online during that timeRe Repost Bitcoin MaturationNovember PMMeritedbyhold coins NeuroticFish ',
'satoshiFounderSr MemberOfflineActivity Merit Re Repost Request Make this anonymousNovember PM There will be a proxy setting in version so you can connect through TOR I ve done a careful scrub to make sure it doesn t use DNS or do anything that would leak your IP while in proxy modesatoshiFounderSr MemberOfflineActivity Merit Re Repost Request Make this anonymousNovember PM There will be a proxy setting in version so you can connect through TOR I ve done a careful scrub to make sure it doesn t use DNS or do anything that would leak your IP while in proxy modesatoshiFounderSr MemberOfflineActivity Merit Re Repost Request Make this anonymousNovember PM There will be a proxy setting in version so you can connect through TOR I ve done a careful scrub to make sure it doesn t use DNS or do anything that would leak your IP while in proxy modeRe Repost Request Make this anonymousNovember PM ',
'satoshiFounderSr MemberOfflineActivity Merit Repost How anonymous are bitcoinsNovember PMMeritedbylivingfree xtraelv bitcoinbitcoin How anonymous are bitcoinsCan nodes on the network tell from which and or to which bitcoin address coins are being sent Do blocks contain a history of where bitcoins have been transfered to and from Can nodes tell which bitcoin addresses belong to which IP addresses Is there a command line option to enable the sock proxy the first time that bitcoin starts What happens if you send bitcoins to an IP address that has multiple clients connected through network address translation NAT satoshiFounderSr MemberOfflineActivity Merit Repost How anonymous are bitcoinsNovember PMMeritedbylivingfree xtraelv bitcoinbitcoin How anonymous are bitcoinsCan nodes on the network tell from which and or to which bitcoin address coins are being sent Do blocks contain a history of where bitcoins have been transfered to and from Can nodes tell which bitcoin addresses belong to which IP addresses Is there a command line option to enable the sock proxy the first time that bitcoin starts What happens if you send bitcoins to an IP address that has multiple clients connected through network address translation NAT satoshiFounderSr MemberOfflineActivity Merit Repost How anonymous are bitcoinsNovember PMMeritedbylivingfree xtraelv bitcoinbitcoin How anonymous are bitcoinsCan nodes on the network tell from which and or to which bitcoin address coins are being sent Do blocks contain a history of where bitcoins have been transfered to and from Can nodes tell which bitcoin addresses belong to which IP addresses Is there a command line option to enable the sock proxy the first time that bitcoin starts What happens if you send bitcoins to an IP address that has multiple clients connected through network address translation NAT Repost How anonymous are bitcoinsNovember PMMeritedbylivingfree xtraelv ']
stop = list(stopwords.words("english"))
stop.append("brand newofflineactivity")
stop.append("newbieofflineactivity")
stop.append("jr. memberofflineactivity")
stop.append("memberofflineactivity")
stop.append("full memberofflineactivity")
stop.append("sr. memberofflineactivity")
stop.append("hero memberofflineactivity")
stop.append("legendaryofflineactivity")
stop.append("vipofflineactivity")
stop.append("donaterofflineactivity")
stop.append("staffofflineactivity")
stop.append("moderatorofflineactivity")
stop.append("global moderatorofflineactivity")
stop.append("administratorofflineactivity")
stop.append("founderofflineactivity")
stop.append("merit")
stop.append("re")
stop.append("bitcoin")
stop.append("bitcoins")
stop.append("brand")
stop.append("full")
stop.append("global")
stop.append("hero")
stop.append("jr")
stop.append("newofflineactivity")
stop.append("sr")
stop.append("pm")
stop.append("com")
stop.append("www")
stop.append("http")
stop.append("")
stpexp = ['*brand newofflineactivity', '*newbieofflineactivity', '*jr. memberofflineactivity',\
'*memberofflineactivity','*full memberofflineactivity','*sr. memberofflineactivity',\
'*hero memberofflineactivity','*legendaryofflineactivity','*vipofflineactivity'\
'*donaterofflineactivity','*staffofflineactivity','*moderatorofflineactivity','*global moderatorofflineactivity',\
'*administratorofflineactivity','*founderofflineactivity']
So I want to search all of the items in 'txt' for all of the variations of the words in the list 'stpexp' and then append all of those variation to my list of stopwords 'stop'.
Any assistance would be greatly appreciated.
You can use the fnmatch built in library.
For example, if you want to find all the words in your text that ends with 'thispattern', you can do it like this:
import fnmatch
txt = ["longerthepattern is the word i want", "thisisthepattern and it works"]
pattern = '*thepattern'
to_add_to_stoplist = []
for sentence in txt:
filters = fnmatch.filter(sentence.split(" "),pattern)
to_add_to_stoplist += filters
And it outputs:
['longerthepattern', 'thisisthepattern']
You can add this list of words to the stopwords.
EDIT:
Here is a version using for comprehensions to analyze multiple patterns. It no longer uses fnmatch and uses the str.endswith function.
Note that it requires the patterns to be a tuple, and not a list.
txt = ["longerthepattern removeme is the word i want", "thisisthepattern and it works"]
patterns = ("pattern","veme")
def my_func(sentence):
return [x for x in sentence.split(" ") if x.lower().endswith(patterns)]
to_add_to_stop = [word for sentence in txt for word in my_func(sentence) ]
It outputs:
['longerthepattern', 'removeme', 'thisisthepattern']
SECOND EDIT:
I added the .lower() fonction in the for comprehension to ensure that the words we are comparing with the patterns are all lowercase since the patterns are lowercase as well.
Related
Hi I have been playing with this code from last 3-4 days but no luck.
Here is the code
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer('all-MiniLM-L6-v2')
sentences3 = ['USPS IV USA Tracking Status WTA Portal to content Home ures Plans About Us Glossary Contact Us Home parceltrack USPS IV USA Tracking Status ',
'UPS Mail Innovations USA Tracking Status to content Home Contact Us Home parceltrack UPS Mail Innovations USA Tracking Status',
'USPS USA Tracking Status | WTA Portal - WTA Portal Skip to cont About Us Glossary Contact Us Home parceltrack USPS USA Tracking Status ']
# remove non ascii characters from list
sentences3 = [x.encode('ascii', 'ignore').decode('ascii') for x in sentences3]
print(sentences3)
embeddings3 = model.encode(sentences3, convert_to_tensor=True)
print(embeddings3)
clusters = util.community_detection(embeddings3, threshold=0.2, min_community_size=1)
print(clusters)
the line clusters = util.community_detection(embeddings3, threshold=0.2, min_community_size=1)
is not outputting anything, I have waited for like 1 hour to see anything happens but no luck. I have descent mac pro m2 with 16gb RAM, so I feel resources shouldn't be an issue.
Anyone got any tips to debug?
Thanks
This was a known issue in SBERT that was supposed to be fixed. But you can get around it by setting a higher threshold. If you set it to 0.8 it runs in seconds. Or by adding more sentences.
util.community_detection(embeddings3, threshold=0.8, min_community_size=1)
I am new to the web scraping. I am trying to scrape "When purchase Online"
When purchased online in the Target. But i did not find it in the HTML.
.
Does anyone konw how to locate the element in HTML? Any help appreciates. Thanks!
Product Url:
https://www.target.com/c/allergy-sinus-medicines-treatments-health/-/N-4y5ny?Nao=144
https://www.target.com/p/genexa-dextromethorphan-kids-39-cough-and-chest-congestion-suppressant-4-fl-oz/-/A-80130848#lnk=sametab
I have no idea which element you want to get but API sends JSON data, not HTML, and you may simply convert it to dictionary/list and use keys/indexes to get value.
But you have to manually find correct keys in JSON data.
Or you may write some script to search in JSON (using for-loops and recursions)
Minimal working code. I found keys manually.
import requests
url = 'https://redsky.target.com/redsky_aggregations/v1/web/pdp_client_v1?key=9f36aeafbe60771e321a7cc95a78140772ab3e96&tcin=80130848&is_bot=false&member_id=0&store_id=1771&pricing_store_id=1771&has_pricing_store_id=true&scheduled_delivery_store_id=1771&has_financing_options=true&visitor_id=01819D268B380201B177CA755BCE70CC&has_size_context=true&latitude=41.9831&longitude=-91.6686&zip=52404&state=IA' # JSON
response = requests.get(url)
data = response.json()
product = data['data']['product']
print('price:', product['price']['current_retail'])
print('title:', product['item']['product_description']['title'])
print('description:', product['item']['product_description']['downstream_description'])
print('------------')
for bullet in product['item']['product_description']['bullet_descriptions']:
print(bullet)
print('------------')
print(product['item']['product_description']['soft_bullets']['title'])
for bullet in product['item']['product_description']['soft_bullets']['bullets']:
print('-', bullet)
print('------------')
for attribute in product['item']['wellness_merchandise_attributes']:
print('-', attribute['value_name'])
print(' ', attribute['wellness_description'])
Result:
price: 13.99
title: Genexa Dextromethorphan Kids' Cough and Chest Congestion Suppressant - 4 fl oz
description: Genexa Kids’ Cough & Chest Congestion is real medicine, made clean - a powerful cough suppressant and expectorant that helps control cough, relieves chest congestion and helps thin and loosen mucus. This liquid, non-drowsy medicine has the same active ingredients you need (dextromethorphan HBr and guaifenesin), but without the artificial ones you don’t (dyes, common allergens, parabens). We only use ingredients people deserve to make the first gluten-free, non-GMO, certified vegan medicines to help your little ones feel better. <br /><br />Genexa is the first clean medicine company. Founded by two dads who believe in putting People Over Everything, Genexa makes medicine with the same active ingredients people need, but without the artificial ones they don’t. It’s real medicine, made clean.
------------
<B>Suggested Age:</B> 4 Years and Up
<B>Product Form:</B> Liquid
<B>Primary Active Ingredient:</B> Dextromethorphan
<B>Package Quantity:</B> 1
<B>Net weight:</B> 4 fl oz (US)
------------
highlights
- This is an age restricted item and will require us to take a quick peek at your ID upon pick-up
- Helps relieve kids’ chest congestion and makes coughs more productive by thinning and loosening mucus
- Non-drowsy so your little ones (ages 4+) can get back to playing
- Our medicine is junk-free, with no artificial sweeteners or preservatives, no dyes, no parabens, and no common allergens
- Certified gluten-free, vegan, and non-GMO
- Flavored with real organic blueberries
- Gentle on little tummies
------------
- Dye-Free
A product that either makes an unqualified on-pack statement indicating that it does not contain dye, or carries an unqualified on-pack statement such as "no dyes" or "dye-free."
- Gluten Free
A product that has an unqualified independent third-party certification, or carries an on-pack statement relating to the finished product being gluten-free.
- Non-GMO
A product that has an independent third-party certification, or carries an unqualified on-pack statement relating to the final product being made without genetically engineered ingredients.
- Vegan
A product that carries an unqualified independent, third-party certification, or carries on-pack statement relating to the product being 100% vegan.
- HSA/FSA Eligible
Restrictions apply; contact your insurance provider about plan allowances and requirements
EDIT:
Information "When purchased online" (or "at Cedar Rapids South") are in different url.
For example
Product url:
https://www.target.com/p/genexa-kids-39-diphenhydramine-allergy-liquid-medicine-organic-agave-4-fl-oz/-/A-80130847
API product data:
https://redsky.target.com/redsky_aggregations/v1/web/pdp_client_v1?key=9f36aeafbe60771e321a7cc95a78140772ab3e96&tcin=80130847&is_bot=false&member_id=0&store_id=1771&pricing_store_id=1771&has_pricing_store_id=true&scheduled_delivery_store_id=1771&has_financing_options=true&visitor_id=01819D268B380201B177CA755BCE70CC&has_size_context=true&latitude=41.9831&longitude=-91.6686&zip=52404&state=IA
API "at Cedar Rapids South":
https://redsky.target.com/redsky_aggregations/v1/web_platform/product_fulfillment_v1?key=9f36aeafbe60771e321a7cc95a78140772ab3e96&is_bot=false&tcin=80130847&store_id=1771&zip=52404&state=IA&latitude=41.9831&longitude=-91.6686&scheduled_delivery_store_id=1771&required_store_id=1771&has_required_store_id=true
But probably in some situations it may use other information in product data to put "When purchased online" instead of "at Cedar Rapids South" - and this can be hardcoded in JavaScript. For example product which displays "When purchased online" has formatted_price $13.99 but product which displays "at Cedar Rapids South" has formatted_price "See price in cart"
import requests
url = 'https://redsky.target.com/redsky_aggregations/v1/web/plp_search_v1?key=9f36aeafbe60771e321a7cc95a78140772ab3e96&brand_id=q643lel65ir&channel=WEB&count=24&default_purchasability_filter=true&offset=0&page=%2Fb%2Fq643lel65ir&platform=desktop&pricing_store_id=1771&store_ids=1771%2C1768%2C1113%2C3374%2C1792&useragent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%3B+rv%3A101.0%29+Gecko%2F20100101+Firefox%2F101.0&visitor_id=01819D268B380201B177CA755BCE70CC' # JSON
response = requests.get(url)
data = response.json()
for product in data['data']['search']['products']:
print('title:', product['item']['product_description']['title'])
print('price:', product['price']['current_retail'])
print('formatted:', product['price']['formatted_current_price'])
print('---')
Result:
title: Genexa Kids' Diphenhydramine Allergy Liquid Medicine - Organic Agave - 4 fl oz
price: 7.99
formatted: See price in cart
---
title: Genexa Dextromethorphan Kids' Cough and Chest Congestion Suppressant - 4 fl oz
price: 13.99
formatted: $13.99
---
I am using a CSV file with news about crypto. My goal is to practice string manipulation and methods. The CSV looks something like this :
publishdate headlinetext
20130504 COnSTELlATIon DaG iS nOW liStEd On kucoiN eXC?haNGE
20130511 ItA*lys cRypTOCUrREnCy BITgrAil suspeNds OpERatIOnS
20130511 THe diffeRENCe bETWEEn sHarEs aNd cRYpToCUrReN€CiES
20130512 fedS seIzE 47 mIlLION In bItCoinS in FAke ID ST=ing
20130514 ThE diG sTarteD ASiCboOST neTwORK AnD b#ItcoIN cAsH
20130516 BINAncE far atualiZAO progRaMadA NEsTa QuarTAFEIR?a
20130516 tHe EUropeaN UniOn IS pLaNninG tO rEgULAtE Bi=TcOIn
20130516 i!BeROBiT HELpiNG bItcOIn To GO MAinStream IN sPaIN
20130521 EuropES sMALLEr €banKS WELComE CrypTOcuRRENCy uSerS
20130604 BiTcoIn btc hIghER bTc= price BRiNgs mOrE Btc SCAmS
20130610 BITCOin brEAkS 9000 iN latEST LANDmARK Pr#iCE pOinT
20130613 ubcoiN mArkEt movEs ItS HEAdQUArTERS To €SiNgaPorE
20130624 reeds jEwelErs TaKinG bitCOiN ONLiNe And IN Sto$Res
20130705 CoNtrOvE!RSY turnS to cLoSuRe as LItePAy SHUts DowN
20130709 bUll rESiSTAncE BITCOIn pRicE nEeDs brEAK AbOve 9K*
20130714 DIVoRcE DISpUte co#Uple fIghtS ovEr 830k Of BITcoin
20130718 10K agaIn For BitcoiN buT oT!her CRyptOs OUTperfORM
20130724 FACebOoKS liBRa crYptoCUrrency wHER$E aRE ThE BANkS
20130726 COULd eNjIn coiN ReacH A neW AlltiM=E hIGh in APRIL
20130827 the GReaT Tug of WaR betWE=eN bItCOiNS anD AltCOINs
20130827 The SacRAMento kINgs mINE EthEreuM ETh for C#HArItY
20130905 cryPtOCuRREncY aTMs tHE KEY T*o WIdeSPRead ADoPtiOn
20130909 GraySCales EtHereUM TRusT pRICE= VaLUeS Eth aT 6000
(...)
Then I used pandas to read the CSV.
import pandas as pd
news_headlines = pd.read_csv('/content/sample_data/crypto_headlines.csv')
news_headlines
Now I need to get the strings to work with them and change them to lower or upper case and then remove special characters.
However , I don't know which method I should use to extract a string from this variable I created called news_headlines.
Let's say I wanted to extract the 2nd row, with the publish date on 20130511.
Any help ?
Thanks in advance
You can use iloc(), as in the example below, to extract the string related to the second row:
news_headlines.iloc[1, 1]
Check the following text piece
IN THE HIGH COURT OF GUJARAT AT AHMEDABAD
R/CRIMINAL APPEAL NO. 251 of 2009
FOR APPROVAL AND SIGNATURE:
HONOURABLE MR.JUSTICE R.P.DHOLARIA
==========================================================
1 Whether Reporters of Local Papers may be allowed to see the judgment ?
2 To be referred to the Reporter or not ?
3 Whether their Lordships wish to see the fair copy of the judgment ?
4 Whether this case involves a substantial question of law as to the interpretation of the Constitution of India or any order made thereunder ?
========================================================== STATE OF GUJARAT,S M RAO,FOOD INSPECTOR,OFFICE OF THE Versus DHARMESHBHAI NARHARIBHAI GANDHI ========================================================== Appearance: MS HB PUNANI, APP (2) for the Appellant(s) No. 1 MR DK MODI(1317) for the Opponent(s)/Respondent(s) No. 1 ==========================================================
CORAM: HONOURABLE MR.JUSTICE R.P.DHOLARIA
Date : 12/03/2019
ORAL JUDGMENT
1. The appellant State of Gujarat has
preferred the present appeal under section 378(1)
(3) of the Code of Criminal Procedure, 1973
against the judgment and order of acquittal dated
Page 1 of 12
R/CR.A/251/2009 JUDGMENT
17.11.2008 rendered by learned 2nd Additional
Civil Judge and Judicial Magistrate, First Class,
Nadiad in Food Case No.1 of 2007.
The short facts giving rise to the
present appeal are that on 10.11.2006 at about
18.00 hours, the complainant visited the place of
the respondent accused situated at Juna
Makhanpura, Rabarivad, Nadiad along with panch
witness and the respondent was found dealing in
provisional items. The complainant identified
himself as a Food Inspector and after giving
intimation in Form No.6 has purchased muddamal
sample of mustard seeds in the presence of the
panchas for the purpose of analysis. Thereafter,
the complainant Food Inspector has divided the
said sample in equal three parts and after
completing formalities of packing and sealing
obtained signatures of the vendor and panchas and
out of the said three parts, one part was sent to
the Public Analyst, Vadodara for analysis and
remaining two parts were sent to the Local Health
Authority, Gandhinagar. Thereafter, the Public
Analyst forwarded his report. In the said report,
it is stated that the muddamal sample of mustard
seeds is misbranded which is in breach of the
provisions of the Food Adulteration Act, 1954
(for short “the Act”) and the Rules framed
thereunder. It is alleged that, therefore, the
sample of mustard seeds was misbranded and,
thereby, the accused has committed the offence.
**Page 2 of 12
R/CR.A/251/2009* JUDGMENT*
Hence, the complaint came to be lodged against
the respondent accused.
I want to be able to write a program such that it follows the given constraints. Be wary of the fact that this is only a single file i have like 40k files and it should run on all the files. All the files have some difference but the basic format for every file is the same.
Constraints.
It should start the text extraction process from after the "metadata" . Metadata is the data about the file from the starting of the file i.e " In the high court of gujarat" till Oral Judgment. In all the files i have , there are various POINTS after the string ends. So i need all these points as a separate paragraph ( see the text has 2 points , i need it in different paragraphs ).
Check the lines in italics, these are the panes in the text/pdf file. I need to remove these as these donot have any meaning to the text content i want.
These files are both available in TEXT or PDF format so i can use either. But i am new to python so i dont know how and where to start. I just have basic knowledge in python.
This data is going to be made into a "corpus" for further processes in building a huge expert system so you know what needs to be done i hope.
Read the official python docs!
Start with python's basic str type and its methods. One of its methods, find, will find substrings in your text.
Use the python slicing notation to extract the portion of text you need, e.g.
text = """YOUR TEXT HERE..."""
meta_start = 'In the high court of gujarat'
meta_end = 'ORAL JUDGMENT'
pos1 = text.find(meta_start)
pos2 = text.find(meta_end)
if pos2 > pos1 and pos1 > -1:
# text is found, extract it
text1 = text[meta_start + len(meta_start):meta_end - 1]
After that, you can go ahead and save your extracted text to a database.
Of course, a better and more complicated solution would be to use regular expressions, but that's another story -- try finding the right way for yourself!
As to italics and other text formatting, you won't ever be able to mark it out in plain text (unless you have some 'meta' markers, like e.g. [i] tags).
Hi~ I am having a problem while I am trying to tokenize facebook comments which are in CSV format. I have my CSV data ready, and I completed reading the file.
I am using Anaconda3; Python 3.5. (My CSV data has about 20k in rows and 1 in cols)
The codes are,
import csv
from nltk import sent_tokenize, word_tokenize as sent_tokenize, word_tokenize
with open('facebook_comments_samsung.csv', 'r') as f:
reader = csv.reader(f)
your_list = list(reader) #list(reader)
print (your_list)
What comes, as a result, is something like this:
[['comment_message'], ['b"Yet again been told a pack of lies by Samsung Customer services who have lost my daughters phone and couldn\'t care less. ANYONE WHO PURCHASES ANYTHING FROM THIS COMPANY NEEDS THEIR HEAD TESTED"'], ["b'You cannot really blame an entire brand worldwide for a problem caused by a branch. It is a problem yes, but address your local problem branch'"], ["b'Haha!! Sorry if they lost your daughters phone but I will always buy Samsung products no matter what.'"], ["b'Salim Gaji BEST REPLIE EVER \\xf0\\x9f\\x98\\x8e'"], ["b'<3 Bewafa zarge <3 \\r\\n\\n \\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x93\\r\\n\\xf0\\x9f\\x8e\\xad\\xf0\\x9f\\x91\\x89 AQIB-BOT.ML \\xf0\\x9f\\x91\\x88\\xf0\\x9f\\x8e\\xadMANUAL\\xe2\\x99\\xaaKing.Bot\\xe2\\x84\\xa2 \\r\\n\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x94\\xe2\\x80\\x93\\xe2\\x80\\x94'"], ["b'\\xf0\\x9f\\x8c\\x90 LATIF.ML \\xf0\\x9f\\x8c\\x90'"], ['b"I\'m just waiting here patiently for you guys to say that you\'ll be releasing the s8 and s8+ a week early, for those who pre-ordered. Wishful thinking \\xf0\\x9f\\x98\\x86. Can\'t wait!"'], ['b"That\'s some good positive thinking there sir."'], ["b'(y) #NextIsNow #DoWhatYouCant'"], ["b'looking good'"], ['b"I\'ve always thought that when I first set eyes on my first born that I\'d like it to be on the screen of a cameraphone at arms length rather than eye-to-eye while holding my child. Thank you Samsung for improving our species."'], ["b'cool story'"], ["b'I believe so!'"], ["b'superb'"], ["b'Nice'"], ["b'thanks for the share'"], ["b'awesome'"], ["b'How can I talk to Samsung'"], ["b'Wow'"], ["b'#DoWhatYouCant siempre grandes innovadores Samsung Mobile'"], ["b'I had a problem with my s7 edge when I first got it all fixed now. However when I went to the Samsung shop they were useless and rude they refused to help and said there is nothing they could do no wonder the shop was dead quiet'"], ["b'Zeeshan Khan Masti Khel'"], ["b'I dnt had any problem wd my phn'"], ["b'I have maybe just had a bad phone to start with until it got fixed eventually. I had to go to carphone warehouse they were very helpful'"], ["b'awesome'"], ["b'Ch Shuja Uddin'"], ["b'akhheeerrr'"], ["b'superb'"], ["b'nice story'"], ["b'thanks for the share'"], ["b'superb'"], ["b'thanks for the share'"], ['b"On February 18th 2017 I sent my phone away to with a screen issue. The lower part of the screen was flickering bright white. The phone had zero physical damage to the screen\\n\\nI receive an email from Samsung Quotations with a picture of my SIM tray. Upon phoning I was told my SIM tray was stuck inside the phone and was handed a \\xc2\\xa392.14 repair bill. There is no way that my SIM tray was stuck in the phone as I removed my SIM and memory card before sending the phone away.\\n\\nAfter numerous calls I finally gave in and agreed to pay the \\xc2\\xa392.14 on the understanding that my screen repair would also be covered in this cost. This was confirmed to me by the person on the phone.\\n\\nOn
Sorry for your inconvenience in reading the result. My bad.
To continue, I added,
tokens = [word_tokenize(i) for i in your_list]
for i in tokens:
print (i)
print (tokens)
This is the part where I get the following error:
C:\Program Files\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py in _slices_from_text(self, text) in line 1278 TypeError: expected string or bytes-like object
What I want to do next is,
import nltk
en = nltk.Text(tokens)
print(len(en.tokens))
print(len(set(en.tokens)))
en.vocab()
en.plot(50)
en.count('galaxy s8')
And finally, I want to draw a wordcloud based on the data.
Being aware of the fact that every seconds of your time is precious, I am terribly sorry to ask for your help. I have been working this for a couple of days, and cannot find the right solution for my problem. Thank you for reading.
The error you're getting is because your CSV file is turned into a list of lists-- one for each row in the file. The file only contains one column, so each of these lists has one element: The string containing the message you want to tokenize. To get past the error, unpack the sublists by using this line instead:
tokens = [word_tokenize(row[0]) for row in your_list]
After that, you'll need to learn some more python and learn how to examine your program and your variables.