01-07-2019, 09:03 PM
(01-07-2019, 06:27 PM)Koen G wrote: You are not allowed to view links. Register or Login to view.I guess essentially I'd need a code that does TTR for x-word chunks.
Your wish is my command.
I just concatenated the x last words with a "." separator. The third and last parameter is x.
Code:
import java.io.*;
import java.util.*;
public class xMATTR
{
static int window;
static List<String> tokens = new ArrayList<String>();
static HashMap<String, Integer> types;
static int nTokens;
static int sumTypes;
static int nLastWords;
static int nLastWordsMinusOne;
static String[] lastWords;
public static void main(String args[])
{
try
{
if (args.length == 3)
{
nLastWords = Integer.parseInt(args[2]);
nLastWordsMinusOne = nLastWords - 1;
lastWords = new String[nLastWords];
window = Integer.parseInt(args[1]);
processFileOrFolder(new File(args[0]));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void processFileOrFolder(File f) throws Exception
{
if (f.exists())
{
if (f.isDirectory())
{
String[] children = f.list();
if (children != null)
{
for (String filename : children)
{
String pathname = f.getPath()+File.separator+filename;
processFileOrFolder(new File(pathname));
}
}
}
else
{
loadFile(f);
System.out.println(f.getPath()+"\t"+computeMATTR());
}
}
}
static void loadFile(File f) throws Exception
{
tokens.clear();
InputStreamReader isreader = new InputStreamReader(new FileInputStream(f), "UTF-8");
BufferedReader reader = new BufferedReader(isreader);
String line;
while((line = reader.readLine()) != null)
{
if (!line.isEmpty())
{
String[] words = line.toLowerCase().replaceAll("\\p{P}", " ").split("[0-9 \t]+");
for (String word: words)
{
if (!word.isEmpty())
{
System.arraycopy(lastWords, 1, lastWords, 0, nLastWordsMinusOne);
lastWords[nLastWordsMinusOne] = word;
if (lastWords[0] != null)
{
String lastWordsAsOne = "";
for (String lastWord: lastWords)
lastWordsAsOne += lastWord + ".";
tokens.add(lastWordsAsOne);
}
}
}
}
}
reader.close();
}
static double computeMATTR()
{
if (tokens.size() < window)
return 0;
nTokens = 0;
types = new HashMap<String, Integer>(window);
for (String token: tokens)
addToken(token);
double m = (double)sumTypes / window / (tokens.size() - window + 1);
return m;
}
static void addToken(String word)
{
incType(word);
nTokens++;
if (nTokens > window)
{
decType(tokens.get(nTokens - window - 1));
sumTypes += types.size();
}
else if (nTokens == window)
{
sumTypes = types.size();
}
}
static void incType(String word)
{
Integer count = types.get(word);
if (count == null)
types.put(word, 1);
else
types.put(word, count + 1);
}
static void decType(String word)
{
Integer count = types.get(word);
if (count == 1)
types.remove(word);
else
types.put(word, count - 1);
}
}

![[+]](https://www.voynich.ninja/images/collapse_collapsed.png)