My aim is to create a sentence consisting of three random words which are to be taken from the columns of a CSV file.
I am having troubles with making PHP choose the words only from the correct columns, hence column one contains the words to be first in the sentence, column two only middle words and column three only last words.
Example of the CSV file:
my;horse;runs
your;chicken;sits
our;dog;barks
Example of the output:
My chicken barks. *reload*
Your horse sits. *reload*
Our dog runs.
My effort so far:
<?php
$file = fopen('input.csv', 'r');
while (($line = fgetcsv($file, 1000, ";")) !== FALSE) {
$x = array_rand($line);
echo $line[$x] . "\n";
}
?>
Thanks in advance and forgive the strong noobness with this one, please.
This gives randomized sentences as requested:
<?php
$file = fopen('input.csv', 'r');
// prepare token contained
$line = array();
// read csv file line by line
while (!feof($file))
// fill single line into token container
$line[] = fgetcsv($file, 1000, ";");
// construct a sentence by picking random words from columns
$sentence = sprintf("%s %s %s\n",
$line[rand(0,sizeof($line)-1)][0],
$line[rand(0,sizeof($line)-1)][1],
$line[rand(0,sizeof($line)-1)][2] );
// output sentence
echo $sentence;
?>
However it is not very efficient, since it reads the whole csv file into memory first. So it only performs on smaller csv files (say up to a few hundred lines). For bigger files you should consider picking the random line number first and reading only that line from the file. Doing this three times gives you three words you can constrcut your sentence from.
I would sort the columns into separate arrays then select a random index.
<?php
$file = fopen('input.csv', 'r');
while (($line = fgetcsv($file, 1000, ";")) !== FALSE) {
$column1[] = $line[0];
$column2[] = $line[1];
$column3[] = $line[2];
}
function pickWord($wordArray){
$x = array_rand($wordArray);
echo $wordArray[$x] . "\n";
}
pickWord($column1);
pickWord($column2);
pickWord($column3);
?>
Something like that
Code
<?php
$csv = "my;horse;runs
your;chicken;sits
our;dog;barks";
$lines = explode( "\n", $csv );
foreach( $lines as $line ) {
echo ucfirst( str_replace( ";", " ", trim( $line ) ) ) . "<br />";
}
?>
Output
My horse runs
Your chicken sits
Our dog barks
Related
I've copied this php:
<?Php
echo "<html><body><table border=1>";
$f = fopen("datos.csv", "r");
$fr = fread($f, filesize("datos.csv"));
fclose($f);
$lines = array();
$lines = explode("\r\n",$fr); // IMPORTANT the delimiter here just the "new line" \r\n, use what u need instead of...
for($i=0;$i<count($lines);$i++) {
echo "<tr>";
$cells = array();
$cells = explode(",",$lines[$i]); // use the cell/row delimiter what u need!
for($k=0;$k<count($cells);$k++) {
echo "<td>".$cells[$k]."</td>";
}
// for k end
echo "</tr>";
}
// for i end
echo "</table></body></html>";
?>
This code generates the html table. I have a csv with one column with diferent values separated with comma, and I want only some values.
The question is the loop with the variable $k to catch only value2, value4, value7 ,...
I appreciate some help, I'm learning php but I start in advanced mode :-(
and I search this site but don't find it.
Its always dangerous to read a whole file into memory, eventually you will find a file that is large enough to blow the script up because it is Too Large to read into memory.
Use fgetcsv() instead in this situation. This reads one line at a time from your csv file, into an array, all you then have to do is pick the occurances (columns) you actually want to process.
if (($handle = fopen("datos.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {
// pick the columns you are interested in
// remember arrays start at index 0
echo sprintf('The bits I am interested in %s, %s, %s<br>',
$data[2], $data[4], $data[7]);
}
fclose($handle);
}
I am trying to parse a csv file into an array. Unfortunately one of the columns contains commas and quotes (Example below). Any suggestions how I can avoid breaking up the column in to multiple columns?
I have tried changing the deliminator in the fgetcsv function but that didn't work so I tried using str_replace to escape all the commas but that broke the script.
Example of CSV format
title,->link,->description,->id
Achillea,->http://www.example.com,->another,short example "Of the product",->346346
Seeds,->http://www.example.com,->"please see description for more info, thanks",->34643
Ageratum,->http://www.example.com,->this is, a brief description, of the product.,->213421
// Open the CSV
if (($handle = fopen($fileUrl, "r")) !==FALSE) {
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row
$c = count($data);
//Populate the array
for ($x = 0; $x < $c; $x++) {
$arrCSV[$key][$x] = $data[$x];
}
$key++;
} // end while
// Close the CSV file
fclose($handle);
}
Maybe you should think about using PHP's file()-function which reads you CSV-file into an array.
Depending on your delimiter you could use explode() then to split the lines into cells.
here an example:
$csv_file("test_file.csv");
foreach($csv_file as $line){
$cell = explode(",->", $line); // ==> if ",->" is your csv-delimiter!
$title[] = $cell[0];
$link[] = $cell[1];
$description = $cell[2];
$id[] = $cell[3];
}
I am beginner in php . In my application i have to read a csv file and store the values of each row in two variables: $name and latin.
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
foreach($data as $value)
{
if($i>8){
// $fgmembersite->InsertUserBirds($value);
echo $value;
}
}
$i++;
echo '<br/>' ;
} fclose($handle);
each row row contains four or three words ( $name is the first and the second word (if the length of row is 4 words) and the $latin store the last two words:
How can i do it to add the array $latin and $name ?
Seems this one is going to do exactly what you need:
$name = $latin = array();
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
if (count($data) === 4) {
$name[] = $data[0];
$name[] = $data[1];
$latin[] = $data[2];
$latin[] = $data[3];
} elseif ($count($data) === 3) {
$name[] = $data[0];
$latin[] = $data[1];
$latin[] = $data[2];
}
}
The best way to handle this data is to look for a more reliable source!
If you have to use this file, try the following:
Use fgets to handle the file line by line.
All species names are lower cased and all Genus names are capitalised so you could search for the rightmost capital letter. Everything from that point on is Latin, everything to the left is Common.
A more elegant approach is to use preg_match to find the last capital letter. I'm not good at regexp so hopefully an improvement can be made on mine, but the below will return your latin name as the last index of the array 'matches'. If you have got this far, you should be able to figure the rest out.
$matches=array();
$pattern="/([A-Z][a-z ]*)*/";
$testdata="Scabies Mite Sarcoptes scabii";
preg_match($pattern,$testdata,$matches);
var_dump($matches);
Although it can seem daunting learning regexp at the same time as PHP, even a little effort will be well rewarded and there are many helpful members on this site.
I've got a list in a text file with the top 1000 words used in the english language. Each line has a list of up to 50 words, like this:
the,stuff,is,thing,hi,bye,hello,a,stuffs
cool,free,awesome,the,pray,is,crime
etc.
I need to write code using that file as input, to make an output file with the a list of pairs of words which appear together in at least fifty different lists. For example, in the above example, THE & IS appear together twice, but every other pair appears only once.
I can't store all possible pairs of words, so no brute force.
I'm trying to learn the language and I'm stuck on this exercise of the book. Please help. Any logic, guidance or code for this would help me.
This is what I have so far. It doesn't do what's intended but I'm stuck:
Code:
//open the file
$handle = fopen("list.txt", 'r');
$count = 0;
$is = 0;
while(!feof($handle)) {
$line = fgets($handle);
$words = explode(',', $line);
echo $count . "<br /><br />";
print_r($words);
foreach ($words as $word) {
if ($word == "is") {
$is++;
}
}
echo "<br /><br />";
$count++;
}
echo "Is count: $is";
//close the file
fclose($handle);
$fp = fopen('output.txt', 'w');
fwrite($fp, "is count: " . $is);
fclose($fp);
This is what I came up with but I think it's too bloated:
plan:
check the first value of the $words array
store the value into $cur_word
store $cur_word as a key in an array ($compare) and
store the counter (line number) as the value of that key
it'll be 1 at this point
see if $cur_word is on each line and if it is then
put the value into $compare with the key as $cur_word
if array has at least 50 values then continue
else go to the next value of the $words array
if it has 50 values then
go to the next value and do the same thing
compare both lists to see how many values match
if it's at least 50 then append
the words to the output file
repeat this process with every word
There are probably 100's of solutions to this problem. Here is one
$contents = file_get_contents("list.txt");
//assuming all words are separated by a , and converting new lines to word separators as well
$all_words = explode(",", str_replace("\n", ",", $contents));
$unique_words = array();
foreach ($all_words as $word) {
$unique_words[$word] = $word;
}
this will give you all the unique words in the file in an array.
You can also use the same technique to count the words
$word_counts = array();
foreach ($all_words as $word) {
if (array_key_exists($word, $word_counts)) {
$word_counts[$word]++;
} else {
$word_counts[$word] = 1;
}
}
then you can loop through and save the results
$fp = fopen("output.txt", "w");
foreach ($word_counts as $word => $count) {
fwrite($fp, $word . " occured " . $count . " times" . PHP_EOL);
}
fclose($fp);
I have csv file "acct-2012-08-24-0001.csv" that contain many lines.I want to count all lines that contain the word "118-bonsplans.com" in line.But I do not know how to count it, I just can count all line in the csv file like the php code as below:
$word = "118-bonsplans.com";
$linecount = count(file('acct-2012-08-24-0001.csv'));
echo $linecount;
I do not know how to do continue.Anyone help me please,
Thanks,
How about:
count(preg_grep("/118\-bonsplans\.com/", file("acct-2012-08-24-0001.csv")));
The first argument to preg_grep is a regular expression pattern. The second is an array to search through. It returns an array of the items in the searched array that matched.
You can try with the following code:
$handle = fopen('acct-2012-08-24-0001.csv', 'r');
$counter = 0;
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
if (stristr($buffer, '118-bonsplans.com')) $counter += 1;
}
fclose($handle);
}
echo $counter;