w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do I strip a line of text or amount of words/characters from stored text with CSS/Javascript?
In JavaScript on a String Object there is a "substring(from, to)" Method, by which you can split Strings at a certain position: http://www.w3schools.com/jsref/jsref_substring.asp So you could use the substring(0,1) Method to split your String at the first letter. Afterwards you could colour the string with the first letter blue. I don't know if that is the simpliest possible Solution, but that's how i would do it. Hope this helps.

Categories : Javascript

A program that opens a text file, counts the number of words and reports the top N words ordered by the number of times they appear in the file?
Use collections.Counter for counting words and open() for opening the file: from collections import Counter def main(): #use open() for opening file. #Always use `with` statement as it'll automatically close the file for you. with open(r'C:Data est.txt') as f: #create a list of all words fetched from the file using a list comprehension words = [word for line in f for word in line.split()] print "The total word count is:", len(words) #now use collections.Counter c = Counter(words) for word, count in c.most_common(): print word, count main() collections.Counter example: >>> from collections import Counter >>> c = Counter('aaaaabbbdddeeegggg') Counter.most_common returns words in sorted order based

Categories : Python

How do I choose a specific line from a file?
$lines = file("Insults.txt"); echo $lines[array_rand($lines)]; Or within a function: function random_line($filename) { $lines = file($filename) ; return $lines[array_rand($lines)] ; } $insult = random_line("Insults.txt"); echo $insult;

Categories : PHP

Change encoding of text file (shell archive or script for antique kernel text to ASCII text, with CRLF, LF line terminators)
Unix uses a single character for line termination. If you want to convert your file with CRLF to single character termination, you can do the following: sed -e 's/<CTRL-V><CTRL_M>//' filename where <CTRL-V> is the Control key pressed with V (do not include < and > characters in the command.

Categories : Bash

How connect words in a text file
awk -F":" '{a[NR]=$0} /^ B:/{print line;line=$2} /^ I:/{line=line" "$2} END{ if(a[NR]!~/^B/) {print line} }' Your_file

Categories : Unix

How to print words ending in "rry" from a text file?
grep rry$ sample.txt Sample.txt: 1 carry 2 car 3 house 4 notebook 5 handbook 6 party 7 hurry 8 rryasdf Prints carry hurry

Categories : Regex

Search for string in text file in-between two key words
You can save ArtistName and SongName as keys in a dictionary using regular expressions if you want. Here are some links to explanations of regular expressions: Python Docs and Tutorials Point import re s = #string you're parsing regex = re.compile(r'w+ = ".*";') matches = regex.findall(s) dict1 = {} for m in matches: elems = m.split(" = ") dict1[str(elems[0])] = elems[len(elems) - 1].strip(';') print (dict1['ArtistName']) print (dict1['SongName']) Output (using your example string): '"FUN."' '"We Are Young"'

Categories : Python

Objective C - Create text file to read and write line by line in Cocoa
Well, to create a file, just use [[NSFileManager defaultManager] createFileAtPath:@"Your/Path" contents:nil attributes:nil]; This creates an empty file, which you can write to or read from. To write text (or XML), just use NSString's writeToFile:atomically:encoding:error: method like this NSString *str = //Your text or XML [str writeToFile:"Your/Path" atomically:YES encoding:NSUTF8StringEncoding error:nil]; To read from a file, just make an NSString with the contents of that file NSString *contents = [NSString stringWithContentsOfFile:@"Your/Path"]; or, if it does not contain a string, get an NSData object from the file NSData *contents = [NSData dataWithContentsOfFile:@"Your/Path"];

Categories : Objective C

Extract a numeric substring and another line as variables from multi-line text file
You could use the following regex for the second line: ^.*(d{6})[^d].*$ Here, the first named sub-group would denote the digits of interest. For example, using Notepad++, Orginal text: Replace options: Resulting text: The regex should remain more or less the same across environments. You might need to simply change the way the named subexpression ($1 here) is referenced.

Categories : Regex

sending text file from server to client line by line in winsocks
You need to also send a newline. getline reads all characters until a newline, but doesn't store the newline in the string. So when you send the string, it doesn't have a newline. You can either send a " " on its own, but probably better to add a newline to the existing string. E.g. : stringToUpper(STRING); STRING += " "; ...

Categories : C++

How to read data from Excel and write it to text file line by line?
You should open the output.txt file with append mode: file = open("Output.txt", "a") Also, you should do this before entering the loop, and it should be closed after that loop. Update: In cases like this one, you could use with instead of closing the file handle at the end. Also including the good suggestion made by @Josh in his own answer, the code could be this: import xlrd import os.path wb = xlrd.open_workbook(os.path.join('D:TRB 2014 Data','SPS1 demo data.xlsx')) wb.sheet_names() sh = wb.sheet_by_index(0) i = 1 with open("Output.txt", "a") as my_file: while sh.cell(i,11).value != 0: Load = sh.cell(i,11).value all_d = sh.col_values(i, 13, 19) DB1 = Load + " " + (" ".join(all_d)) my_file.write(DB1 + ' ') i += 1

Categories : Python

Assigning variables to values in a text file with 3 columns, line by line
while read x y z; do echo x=$x y=$y z=$z done < input.txt The above requires that none of your columns contain any whitespace. EDIT: In response to comments, here is one technique to handle numbering the lines: nl -ba < input.txt | while read line x y z rest; do ~/data/standard/MNI152_T1_2mm -mul 0 -add 1 -roi $x 1 $y 1 $z 1 0 1 point -odt float > NewFile$line done

Categories : Bash

reading a tab delimited text file line by line get data after in vb.net
RichTextBox_WD.Text = String.Join(vbCrLf, File.ReadLines(vcFile).Select(Function(line) Dim format = "RECEIVED ON: {0} FROM: {1} AMOUNT {2}" Dim fields = line.Split(vbTab) Return String.Format(format, fields(0), fields(1), fields(2)) End Function) I prefer to create a Joined extension method on IEnumerable<T> which wraps String.Join (taking a delimiter and an optional transformation delegate), and a Formatted extension method on String which wraps String.Format: RichTextBox_WD.Text = Fil

Categories : Vb.Net

Iterating though a text file in Java so that each line has information about that line
I cleaned up your code a little bit. import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Palindrome { int charCount = 0; int totalWordCount = 0; public static String isPalindrome(String str) { if(str.equals(new StringBuffer().append(str).reverse().toString())) { return "a"; } else { return "not a"; } } public static int getNumberOfWords(String str) { return str.isEmpty() ? 0 : str.split("\s+").length; } public void process(File file) { try { Scanner sc = new Scanner(file); int i = 0; while(sc.hasNextLine()) { i++; String line = sc.nextLine(); int wordCount =

Categories : Java

Compare a text file line by line with a dynamic variable
If I understand the question correctly, this is what you need: File insert = new File("sample.txt"); BufferedReader br = new BufferedReader(new FileReader(insert)); String strLine; Boolean hasLine = false; while ((strLine = br.readLine()) != null) { if(strLine.equals(field)) { hasLine = true; break; } } br.close(); if (!hasLine) { FileWriter fw = new FileWriter(insert, true); BufferedWriter bw = new BufferedWriter(fw); bw.append(field + " "); // assumes field does not already have a newline bw.flush(); bw.close(); } Notice the break;. This will discontinue the while loop, since you already have the answer to what you are looking for. Your original code was doing: for every line: Do I equal field? Yes: goto next line No: append f

Categories : Java

How to delete a line from a text file using the line number in python
You start counting at one, but python indices are always zero-based. Start your line count at zero: for num, line in enumerate(myFile): # default is to start at 0 or subtract one from num, deleting from lines (not line): del lines[num - 1] Note that in order for your .readlines() call to return any lines, you need to either re-open the file first, or seek to the start: myFile.seek(0)

Categories : Python

How to create hyperlink after finding the words from text file
Not sure why you don't just use explode to split up the pieces of each line in the input file, unless the format of the input is different from what you showed. Otherwise you can use file() to read in the input file, which returns an array of lines in the file. Then you can loop through this array and explode every line into two pieces. The first piece is the name, the second the hyperlink. Then just create the link tag and you're all set. Example code: <?php $lines = file('input.txt'); foreach ($lines as $curLine) { $pieces = explode(" ", $curLine, 2); echo sprintf("<a href="%s">%s</a> ", trim($pieces[1]), trim($pieces[0])); } Edit: Just saw your update and noticed you have multiple spaces or other whitespace characters between the tokens on each line. In tha

Categories : PHP

Turning a text file with words and their positions into a sentence
Read the file, appending the word and positions as tuples to a list. Then sort that list, remove the indices and join the words: with open(inputfilename) as inputfile: words = [] for line in inputfile: line = line.strip() if not line or line.startswith('#'): continue word, positions = line.split(':') words.extend((int(p), word) for p in positions.split(',')) print ' '.join([w for p, w in sorted(words)]) Demo: >>> with open(inputfilename) as inputfile: ... words = [] ... for line in inputfile: ... line = line.strip() ... if not line or line.startswith('#'): ... continue ... word, positions = line.split(':') ... words.extend((int(p), word) for p in positions.split(',')) ...

Categories : Python

Read from a text file and parse lines into words in C
It appears that you are separating words by spaces, so I think just while ((c =fgetc(input_file)) != EOF ) { if (isalpha(c)) { c = tolower(c); putchar(c); } else if (isspace(c)) { putchar(' '); } } will work too. Provided your input text won't have more than one space between words.

Categories : C

Node.js: Inserting a line after a particular line in a text file?
Callback in for loop is not a good idea. Try this code - fs.readFile('nginx.conf', function(err, data) { if(err) throw err; //data = data.toString(); var array = data.toString().split(" "); array[4] ='deny '+cli.getValue(options.ip)+':'+cli.getValue(options.port); for(i=0;i<array.length;i++) { fs.appendFileSync('nginx1.conf', array[i]+' '); } });

Categories : Javascript

write a text file in Python, line by line
You have print new_str for every line in test.txt. But you only write one line to the file after the loop. Changing the code to write after each print: outf = open('result.txt', 'w') for line in fileinput.input("test.txt"): new_str = re.sub('[^a-zA-Z0-9 .]'," ", line) print new_str outf.write(new_str + ' ') outf.close() will do what you want.

Categories : Python

write text file line by line python
If you have the Names and Locations as a list, you can do this: data = [('James','Germany'), ('Gail','US'), ('Merkel','Poland')] with open('output', 'w') as f: for name,place in data: f.write("Name=%s Location=%s " % (name, place))

Categories : Python

C++: Read individual lines from text file, sort words alphabetically
At least if I understand what you want correctly, I'd do something like this: Read a line into a string with std::getline. Initialize a std::stringstream from the string Read words from the stringstream into a vector Sort the vector Write the sorted words to the output. Repeat until done.

Categories : C++

How to append text in every line of a file except for the first line
How about: sed -e '2,$ s/$/|Paris/' < abc.txt And including the header: sed -e '1 s/$/|Place/' -e '2,$ s/$/|Paris/' < abc.txt For the last line, you must have an extra blank line in the file. So, delete all lines containing nothing but zero or more spaces: sed -e '/^ *$/ d' -e '1 s/$/|Place/' -e '2,$ s/$/|Paris/' < abc.txt

Categories : File

read a text file line by line
It's all built into StreamReader: using (var sr = new StreamReader(myFile)) { string line; while ((line = sr.ReadLine()) != null) { // line is the text line } }

Categories : File

parsing a text file with first line all 1's and second line all 2's
You can create a vector of vectors as vector<vector<string>> VEC; And keep on adding words to VEC[0] for the first line and then increment the counter as you encounter a newline character to point to VEC[1] and so on.

Categories : C++

How do you find words in a text file and print the most frequent word shown using array?
Consider using a Map<String,Integer> for the word then you can implement this to count words and will be work for any number of words. See Documentation for Map. Like this (would require modification for case insensitive) public Map<String,Integer> words_count = new HashMap<String,Integer>(); //read your line (you will have to determine if this line should be split or is equations //also just noticed that the trailing '!' would need to be removed String[] words = line.split("\s+"); for(int i=0;i<words.length;i++) { String s = words[i]; if(words_count.ketSet().contains(s)) { Integer count = words_count.get(s) + 1; words_count.put(s, count) } else words_count.put(s, 1) } Then you have the number of occurrences

Categories : Java

How to remove duplicate words from a plain text file using unix commands on windows
Put the words on different lines in your file, say, f1.txt. You may refer to How to replace a character for a newline in Vim? for this. Then execute command "sort -u f1.text > f2.txt" Combine the words of f2.txt into a line or lines if required.

Categories : File

How can I join (Shift+J) the next N words to current line, instead of the entire line?
How about letting vim handle the formatting of your comment blocks. gqap does one paragraph. If it doesn't do what you want out of the box, check out :help 'fo (format options) and especially :help 'fo-table. For instance, setting :set fo+=j might help with those C blocks (remove comment leader automatically when joining lines.)

Categories : Vim

Delete/edit/add a line of text from a text file
I would recommend a Streamreader and ReadLine() for reading all lines and a List for saving them. So the code for the reading + saving would be: Dim lineList As New List(Of String)() Dim sr As StreamReader = New StreamReader(path) Do While sr.Peek() >= 0 lineList.add(sr.ReadLine()) Loop Then add some labels (with the text) to your form: For i as Integer = 0 to lineList.Count - 1 Dim Label as New Label lineLabel.Text = lineList.Item(i) lineLabel.Location = New Point(0, 50 * i) 'you can change the 50 to whatever value you want Me.Controls.Add(Label) AddHandler Label.Click, AddressOf Me.Label_Click 'here we add a handler for the label-clicks Next The handler will look like this then: Private Sub Label_Click(ByVal sender As System.Object, ByVa

Categories : Vb.Net

How do I replace a certain line on a text file with diferent text?
You seem to be confusing static and non-static methods: private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { System::String^ txtfile = L"C:\Users\acer\Desktop\aaa.txt"; array<System::String^>^ lineArray = System::IO::File::ReadAllLines(txtfile); System::Collections::Generic::List<System::String^>^ lineList; lineList = gcnew System::Collections::Generic::List<System::String^>(lineArray); lineList->RemoveAt(6); System::IO::File::WriteAllLines(txtfile, fileList->ToArray()); }

Categories : C++

How to update the first line of text in a text file in VB.NET
In C#.Net: var filepath = "/file/path"; var list = File.ReadAllLines(filepath).ToList(); list.Insert(0, String.Format("Records in this file: {0}", list.Count)); File.WriteAllLines(filepath, list); In VB.Net (I think, i dont really use VB) Dim filepath = "/file/path" Dim list = File.ReadAllLines(filepath).ToList() list.Insert(0, [String].Format("Records in this file: {0}", list.Count)) File.WriteAllLines(filepath, list)

Categories : Dotnet

Find the last line in text file and select the first 10 char and print to a new file?
ifstream file; string filename="D:\example.txt"; file.open(filename.c_str()); string line; while(getline(file,line)); Now you have your last line in the string line now send the 10 chars of line to an output file. line.substr(0,10) will fetch the first ten chars.

Categories : C++

batch file to overwrite a line in a text file
These links will help you How to replace BatchSubstitute

Categories : File

reading file line by line , modify the line and write this line on same file. Python
Because you've used .split on the line, you're working with a list of strings. While a string is conceptually just a list of characters, it's still not a list of strings. Try using the .join method of a string to join your array before you write it out, for example: ''.join(["one, two"]) == "onetwo"

Categories : Python

Read text file in Perl word by word instead of line by line
Instead of reading it in one fell swoop, try the line-by-line approach which is easier on your machine's memory usage too (although 300 KB isn't too large for modern computers). use strict; use warnings; my @words; open (my $inFile, '<', 'tagged.txt') or die $!; while (<$inFile>) { chomp; @words = split(' '); foreach my $word (@words) { # process } } close ($inFile);

Categories : Perl

Remove some words replace some other words from a txt file
This should do the trick. You use a list to store the objects you want to delete, and then loop through the list and remove every element in the list from the contents string. Then, you use a dictionary to store the words you have now and the words you want to replace them with. You also loop over those and replace the current words with the replace ones. def replace(): contents = "" deleteWords = ["the ", "and ", "in "] replaceWords = {"ancient": "old", "month":"years", "centuries":"years"} with open("meText.txt") as f: contents = f.read() for word in deleteWords: contents = contents.replace(word,"") for key, value in replaceWords.iteritems(): contents = contents.replace(key, value) return contents

Categories : Python

how to add a new line in a text file using python without
Just change add: def add(x): nl = " " acc = ".acc" xy = x + acc exyz = xy xyz = exyz xxx = str(xyz) tf = open('accounts.dat',"a+") tf.writelines(xxx) tf.writelines(nl) # Write the newline AFTER instead of before the output tf.close() # close is a function so needs to be called by having () at the end. See the comments for what has changed.

Categories : Python

How to delete first and last line from a text file c#?
You can chain the Skip and Take methods. Remember to subtract the appropriate number of lines in the Take method. The more you skip at the beginning, the less lines remain. var filename = "test.txt"; var lines = System.IO.File.ReadAllLines(filename); System.IO.File.WriteAllLines( filename, lines.Skip(1).Take(lines.Length - 2) );

Categories : C#

Deleting a line in a text file
So whats going on? Something like this: line = "----------------------------------- " => "----------------------------------- " a = line => "----------------------------------- " line.delete a ArgumentError: invalid range "-- " in string transliteration The error raised by the delete method is because dashes are used for special character-range syntax: "hellob".delete "a-e" => "hllo" Probably you want to be taking a different approach to solve your goal, but it is difficult to tell what you want, as you don't show what you want to do with the data once lines are removed. Simply processing the line variable just means you have an altered String at that point.

Categories : Ruby



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.