w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Extracting specific values from a from a text file with long lines
cut is always good and fast for these things: $ cut -d"*" -f3 file CP:53 msec CP:59 msec CP:21 msec Anyway, these awk ways can make it: $ awk -F"|" '{print $27}' file | sed 's/*//g' CP:53 msec CP:59 msec CP:21 msec or $ awk -F"||" '{print $14}' file | sed 's/*//g' CP:53 msec CP:59 msec CP:21 msec Or also $ awk -F"*" '{print $3}' file CP:53 msec CP:59 msec CP:21 msec In both, we set the field delimiter to split the string as some specific character | or *. Then we print a certain block of the split text.

Categories : Regex

Reading exact columns of a text file and putting the values/text into a vector
Read a line in. Scan it for the various parts (numbers, first name, middle initial, last name, etc.) Put the elements into a structure that holds all of them. Put pointers to the structures in an array. Using one or more elements as keys, sort the structures as needed.

Categories : C

Windows Batch programming - Reading from a csv file and extracting certain data columns based on first column value
You need to enable delayed expansion: @echo off setlocal EnableDelayedExpansion set "_InputFile=..." for /f "tokens=1-18* delims=," %%A in (%_InputFile%) do ( Set _var1=%%A Set _var2=%%B ... if "!_var1!"=="RH" echo !_var2! )

Categories : Windows

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

Extracting the coordinates associated with voxels from a text file and store in a .mat file
Have a look at the textread function in the Matlab documentation. It is possible to read the text file in a formatted way, e.g. if you set the format to '%u %u %u', the values that you need will be read. You can even store them in vectors if you want.

Categories : Matlab

Is there a way to preserve text formatting in Excel when extracting it from the worksheet with C# and storing the values into strings?
You can get the superscript/subscript information from Excel via the logical flags in the Font Property of the given Range: Range curRange = ws.get_Range("A1"); if(curRange.Font.Superscript) { //It is a superscript } if(curRange.Font.Subscript) { //It is a subscript } The easiest way to represent this in C# winforms is relying on a RichTextBox (you can even make it "look like a label", as suggested in the following link) and on its SelectionCharOffset. With Labels, it is not so straightforward but there are some workarounds. ---------- UPDATE ANSWER TO THE FIRST QUESTION: C# supports formatting through its Objects, not its string type. Excel strings do not support formatting either; the Ranges are the ones in charge of dealing with this. ANSWER TO THE SECOND QUESTION: You c

Categories : C#

Extracting enum values from ctags file
Yes, you can, by filtering the results of the taglist() function, which give you a convenient programmatic access to the tags database. :echo map(filter(taglist('.*'), 'has_key(v:val, "enum") && v:val.enum ==# "fruit"'), 'v:val.name') ['APPLE', 'ORANGE', 'PEAR'] What this does is: Get all tags (.* regular expression) Keep (filter()) all tags that have (has_key()) an enum attribute, and whose name is exactly (==#) fruit. From the resulting objects, select (map()) only the name attribute.

Categories : C

extracting table from text file
read.table and its family now have an option to read text: > df <- read.table(text = paste(my.data, collapse = " ")) > df model npar AICc DeltaAICc weight Deviance 13 P1 19 94 0.00 0.78 9 12 P2 21 94 2.64 0.20 9 10 P3 15 94 9.44 0.02 9 2 P4 11 94 619.26 0.00 9 > summary(df) model npar AICc DeltaAICc weight Deviance P1:1 Min. :11.0 Min. :94 Min. : 0.00 Min. :0.000 Min. :9 P2:1 1st Qu.:14.0 1st Qu.:94 1st Qu.: 1.98 1st Qu.:0.015 1st Qu.:9 P3:1 Median :17.0 Median :94 Median : 6.04 Median :0.110 Median :9 P4:1 Mean :16.5 Mean :94 Mean :157.84 Mean :0.250 Mean :9 3rd Qu.:19.5

Categories : R

extracting lines from a text file
You could use compress to select elements from an iterator: from itertools import compress l = [0, 1, 0, 1, 1, ...] # your list with open('second.txt') as src, open('third.txt', 'w') as dst: dst.writelines(compress(src, l))

Categories : Python

Extracting strings from text file
@echo off SETLOCAL EnableDelayedExpansion for /f "tokens=*" %%a in (compile2.txt) do ( set linec=%%a set linetest=!linec:Compile log of application=! IF NOT [!linec!]==[!linetest!] set app=!linec:Compile log of application: =! set linetest=!linec: Revision=! IF NOT [!linec!]==[!linetest!] set rev=!linec:Version: 1.0 Revision: =! set linetest=!linec:Compile date/time: =! IF NOT [!linec!]==[!linetest!] set when=!linec:Compile date/time: =! ) echo !app! - !rev! @ !when! ENDLOCAL pause Run that and see if that gives you what you want

Categories : Batch File

read two columns from a text file and sort both columns in java
You can go for this approach, Create a List<Item> where Item is a type containing 2 Column values. (x1 and x2) Then write a compareTo(Item o) which compares the x1 values of the two Item objects presented to it in compare, and if that gave a definite answer, returned that answer. public class Item implements Comparable<Item> { private Integer int1; private Integer int2; @Override public int compareTo(Item o) { return int1 > (o.int1); } } Hope this helps.

Categories : Java

Extracting a particular type of string from a text file using nltk
from nltk.corpus import wordnet as wn fish_words = set() fish_types = set() for i in wn.all_synsets(): # if 'fish' exist in a word. x = [j for j in i.lemma_names if "fish" in j] fish_words.update(x) # if a word ends with 'fish' y = [j for j in i.lemma_names if "fish" in j[-4:]] fish_types.update(y) print fish_types print [i.replace("_"," ")[:-4].strip() for i in fish_types] I'm not sure what kind of fish you're looking for but the above methods should give you all the fish you need as long as you depend on WordNetLemmatizer.

Categories : Python

extracting images from a folder based on a text file
In place of copy "%location%\%%a" c:imagelist put if not exist "%location%\%%a" >>missinglist.txt echo %%a and you could put the %%a in the ECHO clause between "rabbit's ears" if that suits your purpose.

Categories : Batch File

Extracting text in two dimensional array from a file in linux
bash doesn't support 2 dimensional arrays, but you can use other bash utilities. For ex. awk has support for 2 dimensional array. Read more about it here: http://porthos.ist.utl.pt/docs/gawk/gawk_9.html#SEC128

Categories : Linux

Extracting contents from specific meta tags that are not closed using BeautifulSoup
Although I'm not sure it will work for every page: from bs4 import BeautifulSoup import urllib page3 = urllib.urlopen("https://angel.co/uber").read() soup3 = BeautifulSoup(page3) desc = soup3.findAll(attrs={"name":"description"}) print desc[0]['content'].encode('utf-8') Yields: Learn about Uber's product, founders, investors and team. Everyone's Private Dri ver - Request a car from any mobile phoneΓÇötext message, iPhone and Android app s. Within minutes, a professional driver in a sleek black car will arrive curbsi de. Automatically charged to your credit card on file, tip included.

Categories : Python

extracting all data from database but "attempt to re-open an already-closed object"
You have to close your cursor in get_All_Ex_Data(), after your loop. The thing you open and close in onPreExecute and onPostExecute is the db helper. Edit : is your database helper a singleton ? You have an example of a singleton here: Using Singleton design pattern for SQLiteDatabase

Categories : Android

Extracting data from a text file while searching through directories recursively
You can do a nested for loop, cycling through the files in the outer loop, and looking for the information line in the log file in the inner loop: @echo off setlocal ENABLEDELAYEDEXPANSION for /f "delims=" %%i in ('dir /b /s log.txt') do ( for /f "tokens=1* delims==" %%j in (%%~si) do ( set _var=%%j set _var=!_var: =! if defined _var ( if /i "!_var!"=="information" ( echo Filename: %%i; Information: %%k ) ) ) ) endlocal This reports the log filename (with its path) and the information after the = sign in each file. You can change the echo line as needed to report what you want to report. FYI - The inner for loop splits each line of the log.txt file into two parts. The first part is the text to the left of the = sign and is accessed via %%j.

Categories : Windows

How to use strings from one text file to search another, and create a new text file with columns from another?
Here's an example, with input files in file1.txt and file2.txt. I cache the contents of file 1, and their associate output file handles in the dictionary 'files', which I then close at the end after the main loop. In the main loop, I read in each line of file2.txt, strip it, and tokenize it on spaces using the split method. I then find the ip address from the first token, and check if its in 'files'. If so, I write the third column to the respective output file. The last loop closes the output file handles. with open('file1.txt') as file1: files = {ip:open(ip + '.txt', 'w') for ip in [line.strip() for line in file1]} with open('file2.txt') as file2: for line in file2: tokens = line.strip().split(' ') ip = tokens[0][3:] if ip in files: file

Categories : Python

Add Text values of Columns B7:b and E7:e and place value on J7:j, just on ONE worksheet
The following will find the last row in Column B on your "Initiating Devices" sheet and write to the correct ranges. Sub CalcTestValues() Dim wb As Workbook Dim ws As Worksheet Dim lastRow As Long Set wb = ThisWorkbook Set ws = wb.Sheets("Initiating Devices") lastRow = ws.Range("B" & ws.Rows.Count).End(xlUp).Row ws.Range("J7:J" & lastRow).Value = Evaluate("=B7:B" & lastRow & "&E7:E" & lastRow) End Sub If you want this to fire when a user is entering data, you'll need the Worksheet_Change event. Here is a good reference to get you started: Worksheet Change Event: Automatically Run Excel Macros When a Cell Changes.

Categories : Excel

Ampersand as a delim in a FOR /F statement
The ampersand is already escaped by double quotes. So more escaping is not necessary and successful: @echo OFF &SETLOCAL for /f "delims=&" %%i in (file) do echo %%i

Categories : Windows

Numbers as factor after read.delim
Try the following instead sub_num <- DF[!is.na(as.numeric(sapply(DF, as.character)))[1:ncol(DF)], ] # V1 V2 V3 V4 # 2 1 2 3 4 # 4 5 6 7 8 As for your sapply statement, sapply(DF, is.numeric), in order to work correctly, it would need as.character sapply(DF, function(X) is.numeric(as.character(X))) But that would not index your DF as you would expect

Categories : R

Matlab reading hex values from text file with non hex values interspersed?
This solution reads 1 million 2-character lines in less than a second on my laptop: fid = fopen('test.txt'); A = textscan(fid,'%2c','CommentStyle','XX'); fclose(fid); A = hex2dec(A{:}); Note the 'CommentStyle' option that skips those lines that start with XX.

Categories : Matlab

Batch, UNC Paths, Delim _ remove trailing path
Here is a simple one liner that works from the command line: for /f "delims=_" %F in (pathdumpunc.txt) do @echo %~dpF Double up the percents to use it in a batch file

Categories : Batch File

Parse CSV file with and aggregate values, multiple columns
Here is one way using itertools.groupby. import StringIO import csv import itertools data = """CITY,AMOUNT,AMOUNT2,AMOUNTn London,20,21,22 Tokyo,45,46,47 London,55,56,57 New York,25,26,27""" # I use StringIO to create a file like object for demo purposes f = StringIO.StringIO(data) fieldnames = f.readline().strip().split(',') key = lambda x: x[0] # the first column will be a grouping key # rows must be sorted by city before passing to itertools.groupby rows_sorted = sorted(csv.reader(f), key=key) outfile = StringIO.StringIO('') writer = csv.DictWriter(outfile, fieldnames=fieldnames, lineterminator=' ') writer.writeheader() for city, rows in itertools.groupby(rows_sorted, key=key): # remove city column for aggregation, convert to ints rows = [[int(x) for x in row[1:]] for row in

Categories : Python

Parsing a text file with multiple columns
This file looks like its tab separated, you should be able to store each line into an array using split on : my @columns = split( " ", $data ); And then you can access your columns by indexing in: my $id = $columns[0]; etc.

Categories : Perl

Extracting out a text variable in a sentence template to be replace by a random text
You can use replaceAll(String regex, String replacement) from String. See javadoc http://docs.oracle.com/javase/6/docs/api/java/lang/String.html String str = text.replaceAll(pattern, "text"); ; You can do this for all your vars, or better yet, use Matcher and Pattern It is described very thoroughly in this blog

Categories : Java

jericho-html - text extracting and incorrect text lenght
It is 44 only, you need to consider all the tags as one character each, spaces as one character each and all the smileys as one character each. H(1)e(2)l(3)l(4)o(5) (6)W(7)o(8)r(9)l(10)d(11) (12):)(13)<br>(14)<br>(15)H(16)e(17)l(18)l(19)o(20) (21)W(22)o(23)r(24)l(25)d(26) (27:((28)<br>(29)<br>(30)H(31)e(32)l(33)l(34)o(35) (36)W(37)o(38)r(39)l(40)d(41) (42);)(43)<br>(44)

Categories : Java

Reading a specific row & columns of data in a text file
#updated L = [] for index, line in enumerate(open('data.txt')): if index <= 4: #skip first 5 lines continue else: L.append(line.split()[2]) #split on whitespace and append value from third columns to list. print(L) #[6.0, 5.0, 7.0]

Categories : Python

Re-order columns in a text file by a specific pattern
Try this: $ cat input SURGERY0001275678image1.jpg SURGERY11134900211image2.jpg SURGERY19257012image3.jpg SURGERY273142590image4.jpg $ awk '{split($1,a,/[[:alpha:]]*/);print a[2]}' input 0001275678 11134900211 19257012 273142590

Categories : Regex

Extracting Values after matching Attribute Values in XSL
There are only some small errors in your xlst. Because the current node for select for the variables in template doc is the doc element you have to remove the doc/. <xsl:variable name="title" select="str[@name='Title']"/> <xsl:variable name="guid" select="str[@name='GUID']"/> <xsl:variable name="desc" select="str[@name='Desc']"/> To add the variable value to the link use: <img src="http://myserver/images/{$guid}" /> Therefore try: <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' > <xsl:output media-type="text/html; charset=UTF-8" encoding="UTF-8"/> <xsl:template match='/'> <html> <head> </head> <body> <table border="1">

Categories : Xml

Adding new column in between existing columns according to data in a text file
Columns are only added at the end, because otherwise it can mess up existing INSERT SQL queries. You should not be concerned about how the db organizes itself - that's the whole point! later on just query out columns at your wanted order..

Categories : C#

Python: Write dictionary to text file with ordered columns
Take advantage of your "order" variable to drive some generators: def dict2txt(D, writefile, column1='-', delim=' ', width=20, order=['mix','meow']): import csv # simplify formatting for clarity fmt = lambda s: '{!s:{}}'.format(s, width) with open(writefile, 'w') as f: writer = csv.writer(f, delimiter=delim) writer.writerow([fmt(column1)] + [fmt(s) for s in order]) for i in D.keys(): writer.writerow([fmt(i)] + [fmt(D[i][k]) for k in order]) The rows are still unordered. So you might want something like: "for i in sorted(D.keys()):"

Categories : Python

I am extracting two columns using a case statement and selecting them into one single column
You should use pno is not null instead of pno!=null in SQL.SQL uses three valued logic, and pno!=null is UNKNOWN, which is not true nor false, but as it is not true, the case is not taken. So your statement should look like select case when (pno is not null) then 'Reconciled' when (pno is null) then 'Forecast1 Generated' when (rno is null) then 'Forecast Generated' when (rno is not null) then 'Actual Generated' end as Status from tablexyz

Categories : SQL

perl script using XML parser to read values in text file and replace it xml file
A solution using XML::XSH2, a wrapper around XML::LibXML. #!/usr/bin/perl use warnings; use strict; use XML::XSH2; open my $INS, '<', 'install.properties' or die $!; while (<$INS>) { chomp; my ($var, $val) = split / = /; # / fix StackOverflow syntax highlighting. $XML::XSH2::Map::ins->{$var} = $val; } xsh << '__XSH__'; open property.xml ; for /properties/entry { set ./text() xsh:lookup('ins', @key) ; } save :b ; __XSH__ The same programme imlemented using only XML::LibXML: #!/usr/bin/perl use warnings; use strict; use XML::LibXML; open my $INS, '<', 'install.properties' or die $!; my %ins; while (<$INS>) { chomp; my ($var, $val) = split / = /; # / fix StackOverflow syntax highlighting. $ins{$var} = $val; } my $xml =

Categories : Perl

How to delete a column/columns of a CSV file which has cell values with a string enclosed in double quotes
With GNU awk version 4 or later, you can use FPAT to define the patterns. gawk '{print $1, $2, $3}' FPAT="([^,]+)|("[^"]+")" OFS="," 44.csv Test: $ gawk '{print $1, $2, $3}' FPAT="([^,]+)|("[^"]+")" OFS="," mycsv.csv column1, column2, column3 12,455,"string with quotes, and with a comma in between" 4432,6787,"another, string with quotes, and with two comma in between" 11,22,"simple string"

Categories : Unix

How do I read in MATLAB a text file of doubles with variable number of columns per line?
Here is a one-liner, broken into several lines for readability C = cellfun(@(x) sscanf(x, '%f').', ... regexp(... regexprep(... fileread('test.txt'), ... '( | $)', ''), ... ' ', 'split'), ... 'uni', 0).';

Categories : Matlab

Macro to iterate through all rows in all columns of a worksheet and compare a cell to copy the row to a text file
You can use the .Offset() method of Range object and vbTab constant to create tab delimited spaces The .Offset(rows, columns) takes 2 parameters. Number of rows up or down of the current cell. To navigate up you give it a negative value to go down a positive one. Same applies to columns except that you use a negative to move left and a positive to go right. vbTab creates a tab between two objects in the context of "this is " & vbtab & " tab delimited" I have modified your comparison method a bit and added the StrComp() function. It is more reliable and you can specify the comparison parameters. Please see how to compare strings in VBA for more details about the = operator in string comparison. I have changed your Sheet4.Range("K1:K300") as this is a bit misleading and wrong

Categories : Excel

How to remove additional Comma in Text file casing data to Mismatch or Overflow to other Columns
The problem is you are stripping the delimiting quotes. CSV files can have values quoted. When you have a comma in the value you need to quote it. In your example, the file already appears to be in CSV format except for the file extension. I don't know if your actual production file is more complicated and requires more formatting. However, in this example it would simply require a file rename. See RFC 4180 for pretty standard specifications. It's a little dense.

Categories : C#

How to specify all columns as "Text" in Text to Columns function in Data tab?
Although it is not exactly what you want (and I see you don't like the idea of scrolling), when you are presented the data preview showing each column as General. You can select the first column header and holding the Shift key scroll to the right and select ALL of the columns at once. Then select Text as the data format. Not the best, but better than selecting each individually.

Categories : Excel

MySQL: get distinct values from two columns and check whether they occur in two other columns of the same table
It is quite easy, you need only to check if a child have became parent... and because each family has two child you need to do it twice (once for child one and another for child two) and you should have the list of all child whom became parents. And after you have them in the list you only need to count them, see no need to complicate what is easy ;) select count (*) from ( select child1 from fam where child1 in (select parent1 from fam union select parent2 from fam) union select child2 from fam where child2 in (select parent1 from fam union select parent2 from fam) );

Categories : Mysql



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